Polymorphism

1. Introduction to Polymorphism

1.1 What is Polymorphism

Polymorphism means “many forms.” In Java, it allows methods or objects to behave differently based on context.

1.2 Types of Polymorphism

  • Compile-time polymorphism
  • Runtime polymorphism

1.3 Importance

  • Improves code flexibility
  • Promotes reusability
  • Simplifies code design

1.4 Real-World Example

A person can have multiple roles:

  • Teacher
  • Parent
  • Employee

2. Method Overloading (Compile-Time Polymorphism)

2.1 Definition

Method overloading occurs when multiple methods have the same name but different parameters.

2.2 Example

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;
    }
}

2.3 Rules

  • Method name must be same
  • Parameters must differ (number or type)
  • Return type alone is not enough

2.4 Advantages

  • Improves readability
  • Reuses method name

3. Method Overriding (Runtime Polymorphism)

3.1 Definition

Method overriding occurs when a subclass provides its own implementation of a method defined in the parent class.

3.2 Example

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

3.3 Rules

  • Same method name
  • Same parameters
  • Same return type
  • Must use inheritance

3.4 Dynamic Method Dispatch

The method to be executed is decided at runtime.

Animal a = new Dog();
a.sound(); // Calls Dog's method

3.5 @Override Annotation

@Override
void sound() {
System.out.println("Dog barks");
}

3.6 Advantages

  • Supports runtime flexibility
  • Enables dynamic behavior

4. Compile-Time vs Runtime Polymorphism

4.1 Compile-Time Polymorphism

  • Achieved using method overloading
  • Decision made at compile time

4.2 Runtime Polymorphism

  • Achieved using method overriding
  • Decision made at runtime

4.3 Differences

FeatureCompile-TimeRuntime
MethodOverloadingOverriding
BindingEarly bindingLate binding
Decision TimeCompile timeRuntime
PerformanceFasterSlightly slower

4.4 Use Cases

  • Overloading → Same operation with different inputs
  • Overriding → Different behavior in subclasses

Conclusion

Polymorphism is a powerful feature in Java that allows flexibility and dynamic behavior in programs. By understanding method overloading and overriding, beginners can write cleaner, more reusable, and scalable code. This concept is widely used in real-world applications and is essential for mastering Object-Oriented Programming.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *