This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance and shadowing

 
Sudhanshu Mishra
Ranch Hand
Posts: 238
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I have a doubt regarding below code snippet


OUTPUT : 9
Now if B extends A,it means that B also has method display().Also, B has a variable 'a' which is same as variable 'a' in parent class.Then why does it happen that we get the output as 9, even though B has inherited display() method and also it's own 'a' variable.
I know that instance variables are not overridden ,but I am really sorry I am unable to relate this fact with this problem.

I request to please be patient with me and give a reply.

Thanks...
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudhanshu Mishra wrote:
Now if B extends A,it means that B also has method display().

No it does not and that's why it prints 9.
You need to override the method in class B.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudhanshu Mishra wrote:Then why does it happen that we get the output as 9, even though B has inherited display() method


Because B doesn't have its own separate copy of that method. A's implementation of that method is invoked, and precisely because variables are not overridden the only "a" variable available to that method is A's "a".
 
Jayesh A Lalwani
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Data members do not get overridden in Java, only functions. Try this

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic