• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overiding class variable through inheritance

 
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic