Polymorphism is confusing me

I have two classes one extending the other. In the parent class(Mammal), I have a variable with value assigned to it and a method. In the sub class(Zebra) I have a parameter with the same name and a method with the same name. When I said Mammal m = new Zebra(); and called m.name and m.makeNoise(); for m.name it is displaying the value in mammal and for m.makeNoise(), it is displaying the value in zebra. I have pasted my code below.
package ch1;

public class ZooKeeper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ZooKeeper().go();
	}
	
	public void go()
	{
		Mammal m = new Zebra();
		System.out.println("Name: "+m.name+" "+"Noise: "+m.makeNoise());
	}

}

class Mammal
{
	String name = "furry";
	String makeNoise()
	{
		return "Generic Noise";
	}
}

class Zebra extends Mammal
{
	String name = "Stripes";
	String makeNoise()
	{
		return "bray";
	}
}

Open in new window

prsubjectAsked:
Who is Participating?
 
for_yanCommented:


This is expected behavior.
Method makeNoise() in Zebra ovrrides the
same method in Mammal
and JVM at runtime determines that this is instance of Zebra
and uses its overriden method

The fileds are not overriden in this way
If this is instance of Mamma it print name as in Mammal
if you cast it to Zebra iot will print name as in Zebra




0
 
for_yanCommented:

This is your program with subsequent cast to Zebra:

package chl;

public class ZooKeeper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ZooKeeper().go();
	}

	public void go()
	{
		Mammal m = new Zebra();
		System.out.println("Name: "+m.name+" "+"Noise: "+m.makeNoise());

        	Zebra z = (Zebra)m;
		System.out.println("Name: "+z.name+" "+"Noise: "+z.makeNoise());
	}

}

class Mammal
{
	String name = "furry";
	String makeNoise()
	{
		return "Generic Noise";
	}
}

class Zebra extends Mammal
{
	String name = "Stripes";
	String makeNoise()
	{
		return "bray";
	}
}

Open in new window


output:

Name: furry Noise: bray
Name: Stripes Noise: bray

Open in new window

0
 
for_yanCommented:

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.
from:
http://home.cogeco.ca/~ve3ll/jatutor5.htm

So it applies to methods, i.e. to behaviors of the objects
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.