Welcome to another brand new post on Core Java tutorial Series, in our last post, we have discussed the importance and how to use the method overriding & method hiding in Java. In this post, we are going to discuss another important feature of the Java OOPS concept, which is polymorphism.
Polymorphism allows us to perform a single action but in different ways. The word polymorphism comes from a Greek language and which means is “Many Forms.” In simple words, we can say that this is the ability of Java programming language by which “we can create functions or reference variables which behave differently in a different programming context.”
What Is Polymorphism?
Because of polymorphism, Java programming language methods can do different things based on the object that is acting upon. In other words, we define one interface and have multiple implementations.
I hope you have got an idea about these important topics. Now let’s move further and understand the different types of polymorphism in Java with examples.
Types of polymorphism in Java
Java programming language supports two types of polymorphism, and that is:
- Static Polymorphism (Compile-time)
- Dynamic Polymorphism (Runtime)
Compile Time Or Static Polymorphism
A polymorphism that is resolved during the compile time is called static polymorphism. Method overloading is an example of compile-time polymorphism.
Method Overloading: This allows us to have more than one method having the same name but different parameter lists where the sequence and data types of parameters are different. For more information, you can refer to our Method Overloading post.
Static Polymorphism Example: Method overloading is one of the ways Java supports static polymorphism.
Write the program and explanation
Dynamic or Runtime Polymorphism
Dynamic Polymorphism is a process which calls to the overridden methods and resolves at runtime. That’s why it is called runtime polymorphism. We have a full post where we have discussed Method Overriding in Java.
Example Program and Explanation
When a user wants to call an overridden method by using a parent class reference, then the type of the object determines which method is going to execute is determined at run time. Since both the classes have the same method at that time, which method is going to call is determined at runtime by JVM.
Ref – article