| Author |
Inheritance and shadowing
|
Sudhanshu Mishra
Ranch Hand
Joined: May 28, 2011
Posts: 201
|
|
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: 127
|
|
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
|
|
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: 1321
|
|
Data members do not get overridden in Java, only functions. Try this
|
 |
 |
|
|
subject: Inheritance and shadowing
|
|
|