Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Runtime Polymorphism

 
Vaibhav Aggarwal
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for replying. Your code has helped me understand the concept.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only too pleased to help, particularly since it took me a long time to understand polymorphism.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic