The output of the pgm is : 2 3 Obj ref b is of type class Base but pointing to Subclass Object . then why is the output not: 3 3 Can u explain the output please
class Test{ public static void main(String [] args){ Base b = new Subclass(); System.out.println(b.x); System.out.println(b.method()); } } class Base{ int x = 2; int method(){ return x; } } class Subclass extends Base{ int x = 3; int method(){ return x; } }
deekasha gunwant
Ranch Hand
Joined: May 06, 2000
Posts: 396
posted
0
hi arijit, i feel i can explain it. as it seems from ur post that u know about the runtime binding of method calls.that's why the call to b.method()calls the method from the sub clas. but note another imp point & that is :-) the call/reference to member variables is resolved at compile time. so when we write b.x, since b is reference of type base at compile time so the member x of base class is referred. b.x /// resolved at compile time b.method() ////resolved at run time hope i was clear do let me know your response regards deekasha
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
the answers are 2 and 3 right. Base b=new SubClass(); b.x // implies b.x variable is in base class.for x prints 2 SubClass s=new SubClass(); s.x // implies s.x variable is in subclass to this problem for prints 3 here comes the question x variable is also there in baseclass base variables are inherited ,it has to print 2 but varible x is also in subclass ,so it is shadowing of varible x in subclass ,so when s.x // 3 is printed b.method () // method is overridden so when return x means sub class variable is printed i hope it is clear
Arijit Kundu
Greenhorn
Joined: Jan 19, 2000
Posts: 19
posted
0
thanks deekasha ,u are very much clear in explaining my doubt . i was a bit confused with the output and was thinking on the same lines . Ur explanation about call/refernces to member variables being reslved at compile time helps in clearing my doubt . thanks once again . bye Arijit