Polymorphism in Java
Polymorphism is the ability of an object to take on many forms. Polymorphism is an important feature of Java OOPs concept and it allows us to perform multiple operations by using the single name of any method (interface). Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for its own type and for the class Object.
Use of Polymorphism in Java
The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.
Java Polymorphism Example
Let us look at an example.
publicinterfaceVegetarian{}publicclassAnimal{}publicclassDeerextendsAnimalimplementsVegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −
- A Deer IS-A Animal
- A Deer IS-A Vegetarian
- A Deer IS-A Deer
- A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal −
Deer d =newDeer();Animal a = d;Vegetarian v = d;Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
Java Polymorphism Implementation
In this example, we’re showcasing the above concept by creating the object of a Deer and assigning the same to the references of superclasses or implemented interface.
interfaceVegetarian{}classAnimal{}publicclassDeerextendsAnimalimplementsVegetarian{publicstaticvoidmain(String[] args){Deer d =newDeer();Animal a = d;Vegetarian v = d;Object o = d;System.out.println(d instanceofDeer);System.out.println(a instanceofDeer);System.out.println(v instanceofDeer);System.out.println(o instanceofDeer);}}
Output
true
true
true
true
Types of Java Polymorphism
There are two types of polymorphism in Java:
- Compile Time Polymorphism
- Run Time Polymorphism
Compile Time Polymorphism in Java
Compile-time polymorphism is also known as static polymorphism and it is implemented by method overloading.
Example: Compile Time Polymorphism
This example has multiple methods having the same name to achieve the concept of compile-time polymorphism in Java.
// Java Example: Compile Time PolymorphismpublicclassMain{// method to add two integerspublicintaddition(int x,int y){return x + y;}// method to add three integerspublicintaddition(int x,int y,int z){return x + y + z;}// method to add two doublespublicdoubleaddition(double x,double y){return x + y;}// Main methodpublicstaticvoidmain(String[] args){// Creating an object of the Main methodMain number =newMain();// calling the overloaded methodsint res1 = number.addition(444,555);System.out.println("Addition of two integers: "+ res1);int res2 = number.addition(333,444,555);System.out.println("Addition of three integers: "+ res2);double res3 = number.addition(10.15,20.22);System.out.println("Addition of two doubles: "+ res3);}}
Output
Addition of two integers: 999
Addition of three integers: 1332
Addition of two doubles: 30.369999999999997
Run Time Polymorphism in Java
Run time polymorphism is also known as dynamic method dispatch and it is implemented by the method overriding.
Example: Run Time Polymorphism
// Java Example: Run Time PolymorphismclassVehicle{publicvoiddisplayInfo(){System.out.println("Some vehicles are there.");}}classCarextendsVehicle{// Method overriding@OverridepublicvoiddisplayInfo(){System.out.println("I have a Car.");}}classBikeextendsVehicle{// Method overriding@OverridepublicvoiddisplayInfo(){System.out.println("I have a Bike.");}}publicclassMain{publicstaticvoidmain(String[] args){Vehicle v1 =newCar();// UpcastingVehicle v2 =newBike();// Upcasting// Calling the overridden displayInfo() method of Car class
v1.displayInfo();// Calling the overridden displayInfo() method of Bike class
v2.displayInfo();}}
Output
I have a Car.
I have a Bike.
Virtual Method and Run Time Polymorphism in Java
In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.
Example: Implementation of Run Time Polymorphism with Virtual Methods
/* File name : Employee.java */publicclassEmployee{privateString name;privateString address;privateint number;publicEmployee(String name,String address,int number){System.out.println("Constructing an Employee");this.name = name;this.address = address;this.number = number;}publicvoidmailCheck(){System.out.println("Mailing a check to "+this.name +" "+this.address);}publicStringtoString(){return name +" "+ address +" "+ number;}publicStringgetName(){return name;}publicStringgetAddress(){return address;}publicvoidsetAddress(String newAddress){
address = newAddress;}publicintgetNumber(){return number;}}
Now suppose we extend Employee class as follows −
/* File name : Salary.java */publicclassSalaryextendsEmployee{privatedouble salary;// Annual salarypublicSalary(String name,String address,int number,double salary){super(name, address, number);setSalary(salary);}publicvoidmailCheck(){System.out.println("Within mailCheck of Salary class ");System.out.println("Mailing check to "+getName()+" with salary "+ salary);}publicdoublegetSalary(){return salary;}publicvoidsetSalary(double newSalary){if(newSalary >=0.0){
salary = newSalary;}}publicdoublecomputePay(){System.out.println("Computing salary pay for "+getName());return salary/52;}}
Now, you study the following program carefully and try to determine its output −
/* File name : VirtualDemo.java */publicclassVirtualDemo{publicstaticvoidmain(String[] args){Salary s =newSalary("Mohd Mohtashim","Ambehta, UP",3,3600.00);Employee e =newSalary("John Adams","Boston, MA",2,2400.00);System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();}}classEmployee{privateString name;privateString address;privateint number;publicEmployee(String name,String address,int number){System.out.println("Constructing an Employee");this.name = name;this.address = address;this.number = number;}publicvoidmailCheck(){System.out.println("Mailing a check to "+this.name +" "+this.address);}publicStringtoString(){return name +" "+ address +" "+ number;}publicStringgetName(){return name;}publicStringgetAddress(){return address;}publicvoidsetAddress(String newAddress){
address = newAddress;}publicintgetNumber(){return number;}}classSalaryextendsEmployee{privatedouble salary;// Annual salarypublicSalary(String name,String address,int number,double salary){super(name, address, number);setSalary(salary);}publicvoidmailCheck(){System.out.println("Within mailCheck of Salary class ");System.out.println("Mailing check to "+getName()+" with salary "+ salary);}publicdoublegetSalary(){return salary;}publicvoidsetSalary(double newSalary){if(newSalary >=0.0){
salary = newSalary;}}publicdoublecomputePay(){System.out.println("Computing salary pay for "+getName());return salary/52;}}
Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.
mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.
Leave a Reply