BhauAutomation

Java Polymorphism Example

Polymorphism in Java allows an object to take many forms. It enables a single interface to represent different data types or behaviors, improving flexibility and code reusability.

What is Polymorphism in Java?

Polymorphism means "many forms." In Java, it refers to the ability of a single function, operator, or object to behave differently based on the context. It’s one of the key principles of Object-Oriented Programming (OOPs).

Types of Polymorphism

Compile-time Polymorphism (Static Binding) is achieved by method overloading. It allows multiple methods with the same name but different parameters in a class.

Runtime Polymorphism (Dynamic Binding) is achieved by method overriding. The call to an overridden method is resolved at runtime, allowing dynamic behavior.

Objectives of Polymorphism

The main objective of polymorphism is to enhance code flexibility and reusability. It supports method overriding and overloading in classes, enabling dynamic method execution at runtime, and reducing code duplication.

Advantages of Polymorphism

Polymorphism improves code maintainability by allowing a single interface to handle different data types. It supports dynamic behavior in applications and encourages loose coupling between classes, making the code easier to extend and manage.

Example: Method Overriding (Runtime Polymorphism)


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

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

// Main class
public class TestPolymorphism {
    public static void main(String[] args) {
        Animal a;         // reference variable of type Animal
        a = new Dog();    // object of Dog
        a.sound();        // Output: Dog barks
    }
}

Example: Method Overloading (Compile-time Polymorphism)


class MathOperation {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class OverloadExample {
    public static void main(String[] args) {
        MathOperation obj = new MathOperation();
        System.out.println("Sum of integers: " + obj.add(5, 10));
        System.out.println("Sum of doubles: " + obj.add(5.5, 3.2));
    }
}

Best Practices

Use polymorphism to simplify code and reduce redundancy. Follow naming conventions for overloaded methods, prefer method overriding when extending functionality, and always keep code readable and maintainable.