read gfg,tutorialpoint,w3schools
Polymorphism is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows a single entity to take multiple forms. It enables the same method or interface to behave differently depending on the object involved. Polymorphism improves code flexibility, reusability, and maintainability.
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.
The word polymorphism means having multiple forms. The term Polymorphism gets derived from the Greek word where poly + morphos where poly means many and morphos means forms.
Polymorphism means "many forms".
It allows the same method to exhibit different behaviors.
It is achieved through method overloading and method overriding.
Polymorphism is another special feature of object-oriented programming (OOPs). The approach which lies beneath this concept is "single interface with multiple implementations." It offers a single interface for controlling access to a general class of actions.
Polymorphism can be achieved in two of the following ways:
Method Overloading(Compile time Polymorphism)
Method Overriding(Run time Polymorphism)
- Static Polymorphism is in other words termed as compile-time binding or early binding.
- Static binding occurs at compile time. Method overloading is a case of static binding and in this case binding of method call to its definition happens at the time of compilation
That is, the same entity (method or operator or object) can perform different operations in different scenarios
polymorphism in Java allows us to create a single method
that will behave differently
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
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
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 = new Deer();
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
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.
interface Vegetarian{}
class Animal{}
public class Deer extends Animal implements Vegetarian{
public static void main(String[] args) {
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
System.out.println(d instanceof Deer);
System.out.println(a instanceof Deer);
System.out.println(v instanceof Deer);
System.out.println(o instanceof Deer);
}
}
Output
true
true
true
true
1. Compile-Time Polymorphism
Compile-time polymorphism also known as static polymorphism, occurs when the method to be executed is determined during compilation. The method that is called is determined by the compiler. Hence, it is also known as compile-time polymorphism.It is primarily achieved through method overloading.
Method selection occurs at compile time.
Improves readability and flexibility.
Compile-time polymorphism is also known as static polymorphism and it is implemented by method overloading.
Method Overloading
Method overloading allows multiple methods with the same name but different parameter lists within the same class. The compiler chooses the appropriate method based on the arguments passed.
The same method will perform different operations based on the parameter.
- To call an overloaded method in Java, it is must use the type and/or the number of arguments to determine which version of the overloaded method actually to call.
- The overloaded methods may have varied return types and the return type single-handedly is insufficient to make out two versions of a method.
- As and when Java compiler encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
- It permits the user to obtain compile time polymorphism with name method name.
- An overloaded method can throw different kinds of exceptions.
- A method which is overloaded can contain different access modifiers.
Syntax:
class Demo {
void show(int a) {
}
void show(int a, int b) {
}
}
Example: Method overloading by changing the number of arguments
class Helper {
static int Multiply(int a, int b)
{
return a * b;
}
static double Multiply(double a, double b)
{
return a * b;
}
}
class Geeks {
public static void main(String[] args)
{
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Explanation: The Multiply method is overloaded with different parameter types. The compiler picks the correct method during compile time based on the arguments.
Variations in Overloading a Method
Overloading method's argument lists might differ in:
Number of parameters passed
Data type of actual parameters
Sequence of data type of actual parameters
2. Runtime Polymorphism
Runtime polymorphism also known as dynamic polymorphism, occurs when the method call is resolved during program execution. It is achieved through method overriding.
Run time polymorphism is also known as dynamic method dispatch and it is implemented by the method overriding.
Method selection occurs at runtime.
Depends on the actual object type.
Method Overriding
Method overriding occurs when a subclass provides its own implementation of a method already defined in its superclass. The overridden method is selected based on the actual object created.
Syntax:
class Parent {
void print() {
}
}
class Child extends Parent {
@Override
void print() {
}
}
Note: At runtime, the method that gets executed depends on the actual object type, not the reference type.
Explanation: when an object of a child class is created, then the method inside the child class is called. This is because the method in the parent class is overridden by the child class. At runtime, the JVM determines which method to execute based on the actual type of the object, not the reference type. If the object is of a child class, the overridden method in the child class is invoked.
Method Overriding
During inheritance in Java, if the same method is present in both the superclass and the subclass. Then, the method in the subclass overrides the same method in the superclass. This is called method overriding.
In this case, the same method will perform one operation in the superclass and another operation in the subclass.
Note: The method that is called is determined during the execution of the program. Hence, method overriding is a run-time polymorphism.
Rules Of Method Overriding
Argument list: The argument list at the time of overriding method need to be same as that of the method of the parent class. The data types of the arguments along with their sequence must have to be preserved as it is in the overriding method.
Access Modifier: The Access Modifier present in the overriding method (method of subclass) cannot be more restrictive than that of an overridden method of the parent class.
The private, static and final methods can't be overridden as they are local to the class.
Any method which is overriding can throw any unchecked exceptions, in spite of whether the overridden method usually method of parent class might throw an exception or not.
Example
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[]) {
child c1 = new child();
c1.work();
}
}
Virtual Method and Run Time Polymorphism in Java
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.
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.
Advantage of Method Overriding
A class can give its specific execution to an inherited method without having the modification in the parent class (base class).
Java Polymorphism and Inheritance
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
Inheritance:use the extends keyword to inherit from a class.
Why And When To Use "Inheritance" and "Polymorphism"?
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Advantages of Polymorphism
Code Reusability: The same method or class works with different object types.
Flexibility: Different objects can be treated as a common superclass type.
Abstraction: Enables working with general types (abstract classes or interfaces) instead of concrete classes.
Dynamic Behavior: Method calls are resolved at runtime based on the actual object type.
Disadvantages of Polymorphism
It can make more difficult to understand the behavior of an object.
This may cause performance issues, as polymorphic behavior may require additional computations at runtime.
Top comments (0)