Consider an interface called Shape which has a draw() method. Two classes Triangle and Circle implements the Shape interface and override the draw() method.
Now in the main I have the following piece of code:
public static void main(String[] args){
Shape shape = new Triangle();
shape.draw();
//Shape shape = new Circle();
//shape.draw();
}
I find this to be an example of polymorphism as we don't know which draw method will be invoked at the runtime. The explanation says While invoking shape.draw() the compiler sees draw() in the Shape interface at compile time, and the JVM invokes draw() in the Triangle class at run time. Same happens for the draw() in the Circle class.
My doubt is, can this be actually called polymorphism? As the new Triangle() or new Circle() hard coded, won't the compiler always know that it is pointing to the child classes' draw() method?
The concept of Runtime polymorphism is best explained with a Factory method, that returns a Shape object based on an input.
Factory method:
public static Shape getShape(int i){
if(i == 1) {return new Triangle();}
else{return new Circle();}
}
Property file:
num:1
Based on the value in the property file, a Shape object is obtained.
public static void main(String[] args){
int x = getFromPropertyFile();
Shape shape = getShape(x); // Shape obtained from a factory method
shape.draw(); //Runtime polymorphism
}
The compiler has no idea which object would be returned. It is determined at Run time by the value provided as input. You can see this kind of implementation in JDBC driver implementations, where the implementation class is determined at run time.
In Your example:
Shape shape = new Triangle();
shape.draw();
Shape shape = new Circle();
shape.draw();
The method binding happens at the compile time i.e which methods can be invoked on a given reference type is decided at the compile time.
The selection of the method’s implementation to execute happens at the run time i.e which implementation of the method to be executed i.e the super class version or one of the subclass’s version is decided at the run time.
I think the more proper example is
List<Shape> lstShape = new ArrayList<Shape>();
lstShape.add(new Circle());
lstShape.add(new Triangle());
...
for (Shape s: lstShape) {
s.draw();
}
Also see: http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With