Java Learner logo

Module 6: Inheritance and Polymorphism

Lesson focus

Polymorphism in Action

Unlock the power of polymorphism to write flexible and scalable code by treating objects of different classes through a common interface.

What is Polymorphism? Polymorphism, which means 'many forms', is the ability of an object to be treated as an object of its superclass. It allows you to write code that can work with objects of multiple types, as long as they share a common superclass.

How it Works: You can declare a variable of a superclass type, but assign it an object of a subclass. Animal myPet = new Dog(); This is possible because a Dog is an Animal.

Runtime Polymorphism (Dynamic Method Dispatch): The magic happens when you call an overridden method. myPet.makeSound(); Even though myPet is declared as type Animal, the JVM knows at runtime that the actual object is a Dog, so it calls the makeSound() method from the Dog class. This is called dynamic method dispatch.

Benefits of Polymorphism:

  • Flexibility: You can write methods that take a superclass type as a parameter, and they will work with any current or future subclass.
  • Extensibility: You can add new subclasses that follow the same contract without changing the code that uses the superclass.

Mini-Exercise: Create an array of Animal objects, but fill it with instances of Dog and Cat. Loop through the array and call the makeSound() method on each object. Notice how the correct method is called for each object type.

public class Main {
    public static void main(String[] args) {
        // The variable is of the superclass type, but the object is the subclass type
        Animal myPet1 = new Dog();
        Animal myPet2 = new Cat();

        // This is polymorphism. The correct makeSound() is called at runtime.
        myPet1.makeSound(); // The dog barks.
        myPet2.makeSound(); // The animal makes a sound. The cat meows.
    }
}

Lesson quiz

If you have `Animal myAnimal = new Dog();`, which method is called when you execute `myAnimal.makeSound()`?

Next lesson →