DEV Community

Ligouri S Tittus
Ligouri S Tittus

Posted on

Polymorphism in java

What is polymorphism?
The ability of something to exist or be treated in multiple ways depending on the context.

Polymorphism allows objects to behave differently based on their specific class type

  • "Poly" = many
  • "Morph" = forms Polymorphism - > Many forms

That means one thing can be used in different ways depending on the situation.

Why we need polymorphism?

Consider a scenario with different types of Shape objects (e.g., Circle, Rectangle). Without polymorphism, _one might need separate methods to draw _each shape: drawCircle(), drawRectangle(). Polymorphism allows for a single draw() method that behaves differently based on the specific Shape object.

// Parent class
class Shape {
    public void draw() {
        System.out.println("Drawing a generic shape.");
    }
}

// Subclass 1
class Circle extends Shape {

    public void draw() {
        System.out.println("Drawing a Circle.");
    }
}

// Subclass 2
class Rectangle extends Shape {

    public void draw() {
        System.out.println("Drawing a Rectangle.");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Shape myCircle = new Circle();
        Shape myRectangle = new Rectangle();

        myCircle.draw();    // Calls Circle's draw() method
        myRectangle.draw(); // Calls Rectangle's draw() method
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, myCircle and myRectangle are both declared as Shape type, but when draw() is called, the specific implementation from Circle or Rectangle is executed at runtime due to polymorphism (specifically, method overriding). This demonstrates how a single method call can exhibit different behaviors based on the object's actual type.

Types of Java Polymorphism

In Java Polymorphism is mainly divided into two types:

  1. Compile-time Polymorphism(Method overloading)
  2. Runtime Polymorphism(Method overriding)

1)Compile time polymorphism (method overloading):

Within a class one (or) more methods having same method names but different in parameters.
It can be differ in numbers of parameters and different in data types.
**
2)Run time polymorphism (method overriding):**
Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.

Reference:https://www.w3schools.com/java/java_polymorphism.asp
https://www.google.com/search?client=ms-android-vivo-terr1-rso2&sca_esv=0cc3b5bc5eb43f9c&sxsrf=AE3TifPuN27XRV1kYEAGBphyaE2yqm_6BA:1756804100770&q=Why+we+need+polymorphism+in+java+with+example&sa=X&sqi=2&ved=2ahUKEwiA-Pai3bmPAxWnzDgGHdZGAbkQ1QJ6BQikARAB&biw=392&bih=751&dpr=2.75

Top comments (0)