DEV Community

Anees Abdul
Anees Abdul

Posted on

Polymorphism in Java

  • Polymorphism means "many forms."
  • Polymorphism is the ability of a method or object to take many forms.

Types of Polymorphism:

1️⃣ Compile-Time Polymorphism (Method Overloading)
2️⃣ Runtime Polymorphism (Method Overriding)

What is Method Overloading:

*Same method name, but different parameters. Parameters must be different (number or type). changing return type → Not allowed.

class Greeting {

    void greet() {
        System.out.println("Hello!");
    }

    void greet(String name) {
        System.out.println("Hello " + name);
    }
}

O/p:
Greeting g = new Greeting();

g.greet();
g.greet("XYZ");
Enter fullscreen mode Exit fullscreen mode

What is Method Overriding:

  • Same method name, same parameters, but different implementation in the child class. Child uses the same method name and the same parameters, but the child changes what it does. That is method overriding.

If the child class has the same method as the parent, Child method gets priority and the parent method is ignored.

class Animal {

    void sound() {
        System.out.println("Animal makes sound");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now child Class

class Dog extends Animal {

    void sound() {
        System.out.println("Dog barks");
    }
}
Enter fullscreen mode Exit fullscreen mode

    public static void main(String[] args) {

        Dog d = new Dog();
        d.sound();
    }

Output:
Dog barks
Enter fullscreen mode Exit fullscreen mode

Top comments (0)