Java Polymorphism

Java polymorphism refers to the ability of an object to take on different forms or behaviors depending on the context in which it is used. It allows objects of different classes to be treated as objects of a common superclass. Polymorphism is one of the fundamental principles of object-oriented programming and is closely related to inheritance.

Polymorphism in Java is achieved through method overriding and method overloading. Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its superclass. Method overloading, on the other hand, involves having multiple methods with the same name but different parameters within a class.

Example

Here’s an example to demonstrate polymorphism in Java:

// Superclass
class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

// Subclass 1
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The dog barks");
    }
}

// Subclass 2
class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The cat meows");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal animal1 = new Dog(); // Creating an instance of Dog but stored in a variable of type Animal
        Animal animal2 = new Cat(); // Creating an instance of Cat but stored in a variable of type Animal

        animal1.makeSound(); // Output: "The dog barks"
        animal2.makeSound(); // Output: "The cat meows"
    }
}

In the example above, we have a superclass called Animal with a method called makeSound(). The Dog and Cat classes are subclasses of Animal that override the makeSound() method with their own implementations.

In the main() method, we create instances of Dog and Cat but store them in variables of type Animal. This is possible because of polymorphism. When we call the makeSound() method on these objects, the appropriate overridden method is called based on the actual type of the object at runtime. This is known as dynamic method dispatch.

As a result, the program outputs “The dog barks” and “The cat meows”. Even though the variables are declared as Animal, the actual behavior is determined by the specific subclass instance that they hold. This is the power of polymorphism in Java, allowing us to write more flexible and reusable code.