File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Overiding class variable through inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overiding class variable through inheritance" Watch "Overiding class variable through inheritance" New topic

Overiding class variable through inheritance

Skanda Raman
Ranch Hand

Joined: Mar 21, 2008
Posts: 205

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

Joined: Feb 23, 2010
Posts: 20
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

Thanks & Regards,
Srikanth Nalam.
Mukund Jahagirdar

Joined: Feb 20, 2010
Posts: 6
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

Joined: Nov 22, 2009
Posts: 26

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.

I agree. Here's the link:
subject: Overiding class variable through inheritance
jQuery in Action, 3rd edition