Java Polymorphism

Java Polymorphism

Polymorphism in Java is an OOP concept that allows objects to take multiple forms. In simple terms, one name can have many forms, depending on how it is used.

Polymorphism improves code flexibility and reusability.


1. Types of Polymorphism in Java

TypeDescription
Compile-time Polymorphism (Method Overloading)Same method name, different parameters (number/type)
Run-time Polymorphism (Method Overriding)Child class provides a specific implementation of a parent class method

2. Compile-Time Polymorphism (Method Overloading)

  • Occurs when multiple methods have the same name but different parameters in the same class.

  • Resolved during compilation.

class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // 15
System.out.println(calc.add(3.5, 2.5)); // 6.0
System.out.println(calc.add(1, 2, 3)); // 6
}
}


3. Run-Time Polymorphism (Method Overriding)

  • Occurs when a child class provides its own implementation of a parent class method.

  • Resolved during runtime using dynamic method dispatch.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println(“Dog barks”);
}
}class Cat extends Animal {
@Override
void sound() {
System.out.println(“Cat meows”);
}
}

public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();

a1.sound(); // Dog barks
a2.sound(); // Cat meows
}
}

📌 Output:

Dog barks
Cat meows

The type of object at runtime decides which method to call.


4. Key Points About Polymorphism

FeatureDescription
Compile-time (Overloading)Same method name, different parameters, resolved at compile time
Run-time (Overriding)Subclass method overrides parent method, resolved at runtime
Improves flexibilitySame method name can perform different tasks
Enables dynamic behaviorEspecially in inheritance hierarchies

5. Advantages of Polymorphism

  1. Code Reusability – Same method name can handle different types.

  2. Flexibility – Allows dynamic method invocation.

  3. Maintainability – Easier to modify and extend programs.

  4. Scalability – Supports OOP design principles like inheritance and abstraction.

You may also like...