the answer is furry bray, correct. This is because instance variables are not overridden ,never. As the reference variable is of type Mammal the value of m.name is decided at the compile time and as the object to which it is pointing is of subtype(which is legal) i.e Mammal m = new Zebra() the method that is called is decided at run-time (in case of overridden methods--dynamic binding) depending on the object the reference variable is pointing to. Hence the answer furry bray.
m and z2 both refer to the same object. But m.name is different from z2.name. I thought that m was just a type (Mammal) and a pointer to an object. So m.name would mean, go to the object which m refers to, and retrieve the value of name from that object. Apparently, I am wrong. Somehow, m maintains its own value of the instance variable 'name', independent of the object it refers to. I think that's kooky.
Remember, Superclass reference variable(In this caseL m) dont refer to instance variables of subclass. As Sudipto pointed, you cannot ovveride instance variable.
But, Superclass reference variable can refer to subclass methods using dynamic binding as above.
So why instance variables cannot be overriden OR why only just reference variable should be overriden.
Think for some time..you will get the answers.
SCJP 1.6, SCWCD 5.0, SCBCD 5.0 [loading..]
Joined: Feb 10, 2009
Himalay says, "Remember, Superclass reference variable(In this caseL m) dont refer to instance variables of subclass." I don't get this. Doesn't a reference variable refer to an object, i.e. an instance? Doesn't an instance variable belong to an instance? It isn't a static variable. So, m refers to an object on the heap. The dot operator goes to that object, right? The object has an instance variable called 'name'. The object (not the class) has a value for that instance variable.
Joined: Feb 10, 2009
I think a Zebra object must actually have two instance variables called 'name' - and which one is visible depends on whether your reference variable thinks it's looking at a Zebra or a Mammal. I'd call this a pathogenic subclass. In fact, I'd advocate making it illegal to do this.
It means a reference variable name is pointing to the newly created String object "mammal".
In the subclass using shadowing(not overriding), you are assigning the same reference variable name to a new object "zebra"
The method names in line3 and line23 differ, so no method overriding happening.