wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes problem in inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "problem in inheritance" Watch "problem in inheritance" New topic
Author

problem in inheritance

Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100

Why does this code give output
B
B
and not
B
A
Thanks
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Looks like you need to take a(nother) look at this


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
anandkumar gangoni
Greenhorn

Joined: May 30, 2004
Posts: 16
the point here is class C inherits the method show() from class B. and second point is call to a method depends on the actual object in the reference at runtime (but plz make a note the method declaration should also exist in the reference type orelse it will give compilation error).

so here a and b references have C object so the ouput will be B followed by B b'coz the method in class B which is inherited by class C and is called at runtime.

Cheers,
Anand.
maha devan
Ranch Hand

Joined: Mar 16, 2004
Posts: 50
Hi Angela

>>B b = new C();
>>b.show();
The method invocation depends on the type of object stored rather than the variable type B.So in the above code B b = new C(), the compiler will first look for the presence of show() method in Class C,if it doesn't finds it, it starts searching in the parent class. So u get B printed in this case.

A a = new C();
a.show();
In this case also samething happens , the search doesn't depend on variable stored but the type of object referred.

cheers
Maha
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: problem in inheritance
 
Similar Threads
multiple inheritance
A class extending a class and implementing an interface with same methods ?
ClassCastException
About polymorphism
Reference Types and Instance Types