Thursday, 5 February 2015


Types of polymorphism in java- Runtime and Compile time polymorphism

Earlier we saw all about Polymorphism in Java. In this tutorial we will cover types of polymorphism in java. There are two types of polymorphism in java- Runtime polymorhism( Dynamic polymorphism) and Compile time polymorphism (static polymorphism).

Runtime Polymorhism( or Dynamic polymorphism)

Method overriding is a perfect example of  runtime polymorphism. In this kind of polymorphism, reference of class X can hold object of class X or an object of any sub classes of class X. For e.g. if class Y extends class X then both of the following statements are valid:
Y obj = new Y();
//Parent class reference can be assigned to child object
X obj = new Y();
Since in method overriding both the classes(base class and child class) have same method, compile doesn’t figure out which method to call at compile-time. In this case JVM(java virtual machine) decides which method to call at runtime that’s why it is known as runtime or dynamic polymorphism.
Lets see an example to understand it better.

No comments:

Post a Comment