We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Polymorphism is confusing me

prsubject
prsubject asked
on
Medium Priority
303 Views
Last Modified: 2012-05-11
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

Comment
Watch Question

Awarded 2011
Awarded 2011
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Awarded 2011
Awarded 2011

Commented:

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

Awarded 2011
Awarded 2011
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.