0
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. but m.name behavior i did not get? Help pl. Thanks in advance.

Edited by __avd: added [code] tags.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by rahul.ch
1

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.

Edited by masijade: n/a

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.