This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills: The software developer's life manual and have John Sonmez on-line!
See this thread for details.
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphic mechanism

 
Mukul Anand
Greenhorn
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose we have two classes A and B.
B inherits from A.
Now see this :


My question is : Can we call all the methods in class B on reference obj??
Or are we restricted to call only those methods which are there in class A ?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47216
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is not polymorphism, but you are right. You can only call the methods which are in A.
 
Mukul Anand
Greenhorn
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So there is a downside of having a superclass reference to your subclass object. You can call only the inherited methods and not your own specific methods. Right?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47216
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now how on earth is the compiler to tell whether it can call the fizz method or the buzz method? It is impossible to tell what the runtime type of sup will be in advance.

You are right: you can only call methods which are declared in the type of the reference. The reference type might be abstract or an interface, in which case the methods might be abstract in the reference type, but must be implemented in the runtime types.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic