As you can see, I have a Base class and a Subclass1 which inherits Base and Subclass2 which inherits Subclass1. I have a reference of Base class to the objects of Subclass1 and Subclass2.
When I invoke the method printVariable() through the references of Base class, I get the correct results, i.e. the methods of objects of respective derived classes get called at runtime, but this does NOT happen for the member variables. It always accesses the member variable of the base class, why is this so ?? Why does NOT JAVA access the member fields of the derived classes instead ??
When you get to the class at the bottom of the inheritance hierarchy, it has two different variables of the same name, one value 20 inherited from its superclass, the other from itself value 30. You will doubtless soon work out why it is a bad idea to have several variables with the same name in subclasses, and only use that sort of code to see what happens if you …
One quick question though, as you said I have two variables with the same name, one with the value 20 and the other with the value 30. Is there any way in JAVA where I can easily print/display the value(s) of all of the components of an object, such as all its variables and the ones derived from its superclass(es), etc. ??
No. You can try super.variable, but that depends on the variable being accessible (bod practice) and on there only being that one variable accessible in the superclass. You cannot write super.super.variable.
Actually I think I was mistaken. You can cast this to the type of the super‑super‑class. ((Foo)this).variable (Only available in instance methods etc)
But if that isn't bad programming, I don't know what is
Hd Shah wrote:. . . Sorry to have asked you stupid question, I now know it is NOT a good programming practice to have the same name variables in inheritance hierarchy as you clearly pointed out here. . . .
It is NOT a stupid question. There was something you didn't know, you asked about it, you learnt what you didn't know and you learnt something else. So it was a good question.
We don't have time for this. We've gotta save the moon! Or check this out: