File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "problem in inheritance" Watch "problem in inheritance" New topic

problem in inheritance

Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100

Why does this code give output
and not
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

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.

maha devan
Ranch Hand

Joined: Mar 16, 2004
Posts: 50
Hi Angela

>>B b = new C();
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();;
In this case also samething happens , the search doesn't depend on variable stored but the type of object referred.

I agree. Here's the link:
subject: problem in inheritance
It's not a secret anymore!