Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overiding class variable through inheritance

 
Skanda Raman
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I implemented below program where there is a super class called as A and B extends A and class C extends B.

Now i am overiding the method available in respective super classes. My question is why does variable ivar always print the value available in class A. The value for ivar is also defined in class B & class C.

Please let me know if i am missing any concept here.

 
Srikanth Nalam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Eeshwar,

This is called as hiding instance variable.

Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression.

Detailed explanation for this behavior is given here
 
Mukund Jahagirdar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi My friend ,

Here in java when you declare any variable, then if you try to override that variable in the sub class then always the vale of the variable will be hinden and thus the value declared in the super class itself will be seen

 
Christiaan Lombard
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Instance variables can not be overridden, they are simply hidden in a subclass when the subclass declares a variable of the same name.
Thus, both variables will still be available and can have different values. The variable you are accessing depends on the reference variable you are using to access the variable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic