olymorphism

Java Polymorphism

Java Polymorphism

Polymorphism is a concept in Java where a single action can behave differently based on the object that it is acting upon. It is classified into two types: compile-time (method overloading) and runtime (method overriding) polymorphism.

Compile-Time Polymorphism (Method Overloading)

class Calculator {
    // Method overloading by changing the number of parameters
    int add(int a, int b) {
        return a + b;
    }

    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("Sum of 2 numbers: " + calc.add(5, 3));
        System.out.println("Sum of 3 numbers: " + calc.add(5, 3, 2));
    }
}
    

Method overloading is a type of compile-time polymorphism where multiple methods with the same name but different parameters exist within a class.

Runtime Polymorphism (Method Overriding)

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

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

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

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal animal = new Dog();  // Runtime polymorphism
        animal.sound();  // Calls the sound() method of Dog

        animal = new Cat();  // Changing the object type
        animal.sound();  // Calls the sound() method of Cat
    }
}
    

Runtime polymorphism occurs when the method that is called is determined at runtime, based on the object type. In this example, the sound() method is called on an Animal reference, but the actual method that gets executed depends on whether the object is a Dog or a Cat.