DEV Community

Arun
Arun

Posted on

Polymorphism in OOPS

✓✓Polymorphism means “many forms”.
✓✓In OOP, it allows one entity (method or object) to perform different tasks in different scenarios.

🔹 Types of Polymorphism in Java:

  1. Compile-time Polymorphism (Method Overloading)

✓✓Same method name but different parameter list.

✓✓Decided at compile time.

  1. Runtime Polymorphism (Method Overriding)

✓✓Same method name, same parameters, but defined in parent and child classes.

✓✓Decided at runtime using dynamic method dispatch. at runtime using dynamic method dispatch.

Program
Method Overloading (Compile-time)

class Calculator {
// Method with 2 parameters
int add(int a, int b) {
return a + b;
}

// Method with 3 parameters
int add(int a, int b, int c) {
    return a + b + c;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();

    System.out.println("Sum of 2 numbers: " + calc.add(10, 20));
    System.out.println("Sum of 3 numbers: " + calc.add(10, 20, 30));
}
Enter fullscreen mode Exit fullscreen mode

}

🔹 Output:

Sum of 2 numbers: 30
Sum of 3 numbers: 60

Example 2: Method Overriding (Runtime Polymorphism)

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {

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

}

class Cat extends Animal {

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

}

public class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
a1 = newDog();
a1.sound();

   a1 = newCat();
   a1.sound();
}
Enter fullscreen mode Exit fullscreen mode

}

🔹 Output:

Dog barks
Cat meows

Top comments (0)