954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Basic doubt of dynamic method invocation

class Mammal {
	String name = "furry";
	String makeNoise() { return "generic noise";}
}

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

public class Zoo {
	public static void main (String[] args) { new Zoo().go();}
	void go() {
		Mammal m = new Zebra();
		System.out.println(m.name + m.makeNoise());
}
}


output: furry bray

My doubt is that why isn't the output stripes bray? I understood the bray part as subclass method gets invoked during runtime. butm.name behavior i did not get? Help pl. Thanks in advance.

rahul.ch
Newbie Poster
6 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

Because variables are not overridden, they are hidden. Meaning it will take the instance variable of the Type that the instance is declared as.

Edit: IOW, as you can see, the first part of that String has nothing to do with method overriding, as no method either sets, nor retrieves the value of the variable. The variable is being set in the class instantiation and being referenced through the instance using the declared type of that instance.

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

Thanks a lot @masijade. My doubt is cleared. Appreciate the help :)

rahul.ch
Newbie Poster
6 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: