Polymorphism in Java With Examples: Static Vs Dynamic Polymorphism
Polymorphism in Java With Examples: Static Vs Dynamic Polymorphism
The main class that contains the main method is the following:
public class TestArtist {
public static void main(String[] args) {
Artist artist = new Artist();
artist.work();
artist.work("Monalisa");
}
}
The right form of the work method is called during compile time. This is what we call static binding.
In fact, this is method overloading in java.
After the execution of the main method we will get the following output:
I am making an artistic work
I am making an artistic work called Monalisa
ClassB inherits from classA and provides its own implementation of method1
ClassC inherits from classA and provides its own implementation of method1
We say that ClassB and ClassC override the method1 defined in the parent class (classA).
The relationship between an object of child type and and object of the parent type is IS A:
But, the reverse is incorrect: an object of type ClassA is not an Object of class ClassB or ClassC.
An object in java has many forms:
The form of its effective class (it may be more than two forms because all the classes in java
inherits from the Object class)
The java language here uses dynamic binding. This means that the method to call is determined at
the runtime. The method related to the effective type of the object is called.
In our example, the method method1 of the class ClassB is called.
Remark:
Lets suppose that the java language will use static binding which is not the case.
In this case, the method to call is determined during compile time. So, the method to call is
determined based on the type of the declared variable (ClassA).
In this case (static binding), the method method1 of the class ClassA will be called.
I hope that I am not confusing you. But, I want to explain what will be done if java uses static binding
when calling overridden methods.
This is the Painter class that inherits from the Artist class:
public class Painter extends Artist{
public void work(String name){
System.out.println("I am creating a new board called "+ name);
}
}
This is is the Singer class that inherits from the Artist class:
public class Singer extends Artist {
public void work(String name){
System.out.println("I am singing a new song called "+ name);
}
}
The ouput obtained after executing the main class is the following:
I am creating a new board called Monalisa
The method work of the Painter class is executed.
The dynamic binding dictates that the method of the effective type (Painter) gets called.
The dynamic binding occurs during runtime.
artists.get(i).work();
}
}
}