wood burning stoves 2.0*
The moose likes Java in General and the fly likes Polymorphic mechanism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Polymorphic mechanism" Watch "Polymorphic mechanism" New topic
Author

Polymorphic mechanism

Mukul Anand
Greenhorn

Joined: Nov 28, 2012
Posts: 28
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

Joined: Oct 13, 2005
Posts: 36486
    
  16
That is not polymorphism, but you are right. You can only call the methods which are in A.
Mukul Anand
Greenhorn

Joined: Nov 28, 2012
Posts: 28
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

Joined: Oct 13, 2005
Posts: 36486
    
  16
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polymorphic mechanism
 
Similar Threads
can't understand super keyword behavior
SCJP: Threads Qs
Swapping of Object in Java
Method calling
Can we call a class method using interface reference