| 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
|
|
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
. 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
|
|
|
Only too pleased to help, particularly since it took me a long time to understand polymorphism.
|
 |
 |
|
|
subject: Runtime Polymorphism
|
|
|