This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Runtime Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply 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: 32692
    
    4
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: 32692
    
    4
Only too pleased to help, particularly since it took me a long time to understand polymorphism.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Runtime Polymorphism
 
Similar Threads
Anonymous Classes
Reg:use of interface in realtime environment
means Polymorphic method call
inner class concept...doubt
Polymorphism Confusion