olymorphism

Java Polymorphism

Java Polymorphism

Polymorphism is the ability of a single object to take on many forms. In Java, polymorphism is most commonly used when a subclass overrides a method of its superclass.

Method Overloading (Compile-Time Polymorphism)

class Calculator {
    // Overloaded method for adding two integers
    int add(int a, int b) {
        return a + b;
    }

    // Overloaded method for adding three integers
    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 3));  // Calls the two-parameter add method
        System.out.println(calc.add(1, 2, 3));  // Calls the three-parameter add method
    }
}
    

Method overloading is a type of compile-time polymorphism. In this example, the add() method is overloaded to accept different numbers of parameters.

Method Overriding (Runtime Polymorphism)

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

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

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();  // Animal reference and object
        Animal myDog = new Dog();  // Animal reference but Dog object

        myAnimal.sound();  // Outputs: Animal makes a sound
        myDog.sound();  // Outputs: Dog barks
    }
}
    

In method overriding, the subclass provides a specific implementation of the method that is already defined in its superclass. In this example, the sound() method is overridden in the Dog class.