• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphic mechanism

 
Mukul Anand
Greenhorn
Posts: 29
  • 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: 49827
69
  • 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
  • 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: 49827
69
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic