aspose file tools*
The moose likes Beginning Java and the fly likes Runtime Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Runtime Polymorphism" Watch "Runtime Polymorphism" New topic
Author

Runtime Polymorphism

Vaibhav Aggarwal
Greenhorn

Joined: Sep 12, 2007
Posts: 8
Hello,

I am writing a code could someone help me understand it.

class SuperClass{

void display(){
System.out.println("In SuperClass");
}
}

class SubClass extends SuperClass{

void display(){
System.out.println("In SubClass");
}

public static void main(String[] args){
SuperClass obj = new SubClass();
obj.display();
}
}

1) Is this example of "Runtime Polymorphism" ?
2) If it so then why is it called so - I can't understand that if we writing in the code that "obj = new SubClass();" than the compiler would know that "obj.display()" would call the method of SubClass, so shouldn't it be "compiletime polymorphism".
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
Welcome to the Ranch.

Yes, it is runtime polymorphism. The compiler compiles all the classes, and as somebody said here last week "each object has two types, its declared type and its actual type." So your SubClass object. has a declared type of SuperClass and an actual type of SubClass. The runtime checks the actual type of an object and uses methods appropriate to that type.

Try this:

Run with
java SubClass2 1
. Try changing the number, see what happens for odd and even number.
Vaibhav Aggarwal
Greenhorn

Joined: Sep 12, 2007
Posts: 8
Thanks for replying. Your code has helped me understand the concept.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
Only too pleased to help, particularly since it took me a long time to understand polymorphism.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Runtime Polymorphism
 
Similar Threads
inner class concept...doubt
means Polymorphic method call
Anonymous Classes
Polymorphism Confusion
Reg:use of interface in realtime environment