File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Inheritance and shadowing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance and shadowing" Watch "Inheritance and shadowing" New topic
Author

Inheritance and shadowing

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 217

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

Joined: Nov 04, 2009
Posts: 142

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.


SCJP, SCWCD, SCJD
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
Bartender

Joined: Jan 17, 2008
Posts: 2397
    
  28

Data members do not get overridden in Java, only functions. Try this

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inheritance and shadowing