Polymorphism

Polymorphism is what makes inheritance powerful. Polymorphism allows the suprclass reference object to call methods on the subclass methods.

Let's see an example to illustrate Animal.java

public class Animal {
    void makeSound(){
        System.out.println("Animal making a sound");
    }
}

Cat.java

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

Horse.java

public class Horse extends Animal{
    @Override
    void makeSound() {
        System.out.println("Neigh");
    }
}

Dog.cat

public class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

The three animals Dog, Cat and Horse all extends the Animal class and have all overriden the makeSound method

Let's see the power of polymorphism by using an animal reference to call the subclass makeSound method. Main.java

public class Main {
    public static void main(String[] args) {
        Animal[] animals = { new Horse(), new Cat(), new Dog(), new Animal() };
        for (Animal animal: animals) {
            animal.makeSound();
        }
    }
}

Output :

Neigh

Meow

Bark

Animal making a sound

We declared an array of type Animal and stored Animal descendants but we were able to call the specific makeSound method on the Animal class.

Since a Dog, Horse and Cat are Animals, we can use store them in the Animal reference. When the call is made, the appropriate method to be called is determined at runtime. This is also called dynamic method dispatch or virtual method invocation.

results matching ""

    No results matching ""