Back to: Java Tutorials For Beginners and Professionals
Polymorphism in Java with Examples
In this article, I am going to discuss Polymorphism in Java with Examples. Please read our previous where we discussed Wrapper Classes in Java with Examples. It is one of the primary pillars of the object-oriented programming concept. At the end of this article, you will understand the following pointers in detail as well as at the end we will discuss frequently asked interview questions related to Polymorphism, Method Overloading, and Method Overriding in Java.
- What is Polymorphism?
- Why we need Polymorphism?
- Types of Polymorphism in Java?
- What is Compile-Time Polymorphism?
- What is Runtime Polymorphism?
- Understanding Method Overloading and Overriding in Java.
What is Polymorphism in Java?
Polymorphism is a Greek word where poly means many or several and morph means faces/ behaviors or functionalities. So, in simple words, we can say that polymorphism is the ability of an entity to take several forms. In order to understand polymorphism better, please have a look at the following image:
As you can see in the above image, the vehicle is something that has several forms like a two-wheeler, three-wheeler, and four-wheeler, and so on. So this is one example of polymorphism.
According to the software standard, Polymorphism means one function with multiple functionalities or representations. In object-oriented programming, it refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows a common data-gathering message to be sent to each class. Any Java object that can pass more than one IS-A test is considered to be polymorphic.
Polymorphism allows us to create consistent code. Polymorphism encourages called ‘extendibility’ which means an object or a class can have its uses extended. Polymorphism makes software applications a third-party independent applications.
Technically we can say that when a function shows different behaviors when we passed different types and number values, then it is called polymorphism. So behaving in different ways depending on the input received is known as polymorphism i.e. whenever the input changes, automatically the output or the behavior also changes.
The benefits of third-party independent application are as follows:
- In future enhancements migrating from one-third party to another third party is the easiest task.
- It reduces the development time of the application.
- It decreases maintenance support.
- It makes the application more dynamic.
Types of Polymorphism in Java:
Polymorphism is of two types in Java:
- Static polymorphism / compile-time polymorphism / Early binding
- Dynamic polymorphism / Run-time polymorphism / Late binding
The following images show the different types of polymorphisms in Java with their examples.
What is Compile-Time Polymorphism in Java?
It is also known as Static Polymorphism or Early Polymorphism. A polymorphism that is resolved during compile time is known as compile-time polymorphism. The compile-time Polymorphism feature is implemented with static binding. In Java, compile-time polymorphism is achieved through method overloading.
In the case of compile-time or static polymorphism, the object of the class recognizes which method to be executed for a given method call at the time of compilation and binds that method call with method definition.
In Java, this is happening in the case of method overloading because in the case of overloading each method will have a different signature and based on the method call we can easily recognize the method which matches the method signature.
Method Overloading in Java:
Defining a method multiple times with the same name in a single class with different parameter types then we can say that method is overloading. There are two ways to overload the method in java
- By changing the number of arguments
- By changing the data type
Example of Method Overloading in Java:
public class Overloading { public static void main (String[]args) { System.out.println (10); System.out.println (true); //System.out.println(10, true); //error System.out.println (); //leaves blank line System.out.println (10.89); } }
Output:
10
true
10.89
What is Runtime Polymorphism in Java?
It is also known as Dynamic Polymorphism or Late Polymorphism. A polymorphism that is resolved during run time is known as dynamic polymorphism. The Dynamic Polymorphism feature is implemented with dynamic binding. In Java, dynamic polymorphism is achieved through method overriding.
In the case of Runtime Polymorphism for a given method call, we can recognize which method has to be executed exactly at runtime but not in compilation time because in case of overriding we have multiple methods with the same signature.
So, which method to be given preference and executed that is identified at Runtime and binds the method call with its suitable method. It is also called dynamic polymorphism or late binding. Dynamic Polymorphism is achieved by using method overriding.
Method Overriding in Java:
Method Overriding is redefining the method from the superclass into the subclass by adding new functionality or code. In Java, using the overriding concept superclass provides the freedom to the subclass for writing their own code instead of binding on superclass behavior or code.
Usage of Method Overriding in Java:
Method overriding is used to provide the specific implementation of a method that is already provided by its superclass. Method overriding is used for runtime polymorphism.
Rules for Method Overriding in Java:
- The method name must be the same.
- Method parameter types must be the same.
- The method return type must be the same.
Example to Understand Method Overriding in Java:
class connection { void connect () { } } class oracleconnection extends connection { void connect () { System.out.println ("Connected to Oracle"); } } class mysqlconnection extends connection { void connect () { System.out.println ("Connected to MySQL"); } } class Overriding { public static void main (String args[]) { oracleconnection a1 = new oracleconnection (); mysqlconnection b1 = new mysqlconnection (); a1.connect (); b1.connect (); } }
Output:
Connected to Oracle
Connected to MySQL
Advantages of Polymorphism in Java:
- More flexible and reusable code.
- The single variable name can be used to store variables of multiple data types.
- Faster and efficient code at Runtime.
- Code that is protected from extension by other classes.
- More dynamic code at runtime.
Static and Dynamic Bindings in java:
If you have more than one method of the same name or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of their reference in code. This problem is resolved using static and dynamic binding in Java.
Binding is a mechanism to link between a method call and method actual implementation. Its process is used to a link which method or variable to be called as a result of their reference in code.
Static Binding in Java:
When the type of the object is determined at the compiled time (by the compiler), it is known as static binding. The binding of all the static, private, and final methods is done at compile-time.
Why binding of static, final, and private methods is always static binding?
Because the compiler knows that all such methods cannot be overridden and will always be accessed by the object of a local class. Hence compiler doesn’t have any difficulty determining the local object of the class. Static binding is better performance-wise (no extra overhead is required).
Example to Understand Static Binding in Java:
public class StaticBinding { public static class superclass { static void print () { //print in superclass System.out.println ("Hi!"); } } public static class subclass extends superclass { static void print () { //print in subclass System.out.println ("Hello!"); } } public static void main (String[]args) { superclass A = new superclass (); superclass B = new subclass (); A.print (); B.print (); } }
Output:
Hi!
Hi!
Dynamic Binding in Java:
When the type of the object is determined at run time, it is known as dynamic binding. In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.
Example to Understand Dynamic Binding in Java:
public class Main { public static class superclass { void print () { //print in superclass System.out.println ("Hi!"); } } public static class subclass extends superclass { @Override void print () { //print in subclass System.out.println ("Hello!"); } } public static void main (String[]args) { superclass A = new superclass (); superclass B = new subclass (); A.print (); B.print (); } }
Output:
Hi!
Hello!
What is Method Overloading or Function Overloading in Java?
Method Overloading in Java is nothing but a process of creating multiple methods in a class with the same name but with a different signature. In Java, It is also possible to overload the methods in the derived classes as well. It means it allows us to create a method in the derived class with the same name as the method name defined in the base class.
In simple words, we can say that the Method Overloading in Java allows a class to have multiple methods with the same name but with a different signature.
When should we overload methods in Java?
If you want to execute the same logic but with different types of arguments i.e. different types of values, then you need to overload the methods. For example, if you want to add two integers, two floats, and two strings, then you need to define three methods with the same name.
What are the advantages of using method overloading in Java? Or what are the disadvantages if we define methods with a different name?
If we overload the methods, then the user of our application gets comfort feeling in using the method with the impression that he/she calling one method bypassing different types of values. The best example for us is the system-defined “println()” method. It is an overloaded method, not a single method taking different types of values.
When is a method considered as an overloaded method in Java?
If two methods have the same name then those methods are considered overloaded methods. Then the rule we need to check is both methods must have different parameter types/numbers/orders. But there is no rule on return type, non-accessibility modifier and accessibility modifier means overloading methods can have their own return type, non-accessibility modifier, and accessibility modifier because overloading methods are different methods.
Can we overload methods in the same class?
Yes, it is possible. No Compile Time Error, no Runtime Error. Methods can be overloaded in the same or in the super and subclasses because overloaded methods are different methods.
But we can’t override a method in the same class. It leads to Compile Time Error: “method is already defined” because overriding methods are the same methods with a different implementation.
What is Function Overriding in Java?
The process of re-implementing the superclass non-static method in the subclass with the same prototype (same signature defined in the superclass) is called Function Overriding or Method Overriding in Java. The implementation of the subclass overrides (i.e. replaces) the implementation of superclass methods.
The point that you need to keep in mind is the overriding method is always going to be executed from the current class object. The superclass method is called the overridden method and the sub-class method is called the overriding method.
When do we need to override a method in Java?
If the superclass method logic is not fulfilling the sub-class business requirements, then the subclass needs to override that method with the required business logic. Usually, in most real-time applications, the superclass methods are implemented with generic logic which is common for all the next level sub-classes.
When is a sub-class method treated as an overriding method?
If a method in the sub-class contains the same signature as the superclass non-private non-static method, then the subclass method is treated as the overriding method and the superclass method is treated as the overridden method.
Difference Between Method Overloading and Method Overriding in Java
Method Overloading in Java | Method Overriding in Java |
More than one method with the same name, different prototypes in the same scope is known as Method Overloading. | More than one method with the same name, the same prototype in different scope is known as Method Overriding. |
Parameters must be different. | Parameters must be the same. |
It is also known as compile-time polymorphism. | It is also known as run time polymorphism |
It is performed within the class. | It occurs in two classes. |
The return type can be the same or different. | The return type must be the same. |
Static methods can be overloaded. | Static methods cannot be overridden. |
Static Binding is being used for overloaded methods. | Dynamic binding is being used for overridden methods. |
Difference Between Static Polymorphism and Dynamic Polymorphism in Java:
Static Polymorphism in Java | Dynamic Polymorphism in Java |
A type of polymorphism that collects the information to call a method during compile time. | A type of polymorphism that collects the information to call a method during run time. |
Occurs at Compile time. | Occurs at Run time. |
Known as Static Binding or Early Binding. | Known as Dynamic Binding or Late Binding. |
The execution speed is high. | The execution speed is low. |
Example: Method Overloading | Example: Method Overriding |
Difference Between Static Binding and Dynamic Binding in Java:
Static Binding in Java | Dynamic Binding in Java |
It is a binding that happened at compile time. | It is a binding that happened at run time. |
The actual object is not used for binding. | An actual object is used for binding. |
Private, static, and final methods show static binding because they cannot be overridden. | Other than private, static, and final methods show static binding because they can be overridden. |
In the next article, I am going to discuss Encapsulation in Java with Examples. Here, in this article, I try to explain Polymorphism in Java with Examples. I hope you enjoy this Polymorphism in Java with Examples article.