Polymorphism

In this exercise, you will learn the concept of **Polymorphism** in Java, a key principle of **object-oriented programming** that allows an object to take different forms. Through practical examples, you will see how a base class can define common behavior, while derived classes can override those methods to provide specific implementations. Polymorphism facilitates code reuse and improves application flexibility. Through this exercise, you will learn how to apply polymorphism to your Java programs to improve their structure and efficiency.

Topic

Object-Oriented Programming (OOP)

Java Exercise

In this exercise, you will create a Java program that uses **Polymorphism** to handle different types of objects that share common behavior but have specific implementations. First, you will define a base class called Animal with a method called makeSound(). Then, you will create several derived classes such as Dog and Cat, which will override this method to provide their own sounds. Finally, you'll learn how to use a variable of type Animal to store instances of different derived classes and execute overridden methods dynamically.

Instructions:

  1. Create a base class named Animal with a makeSound() method that prints a generic sound.
  2. Create at least two derived classes, such as Dog and Cat, that override the makeSound() method to print specific sounds, such as "Woof!" and "Meow!" respectively.
  3. In the main method, create instances of Dog and Cat using a variable of type Animal and call the makeSound() method in both cases.

This exercise will help you understand how **Polymorphism** allows the same method to behave differently depending on the object that invokes it, which is essential for creating more flexible and reusable Java applications.


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

public class Dog extends Animal {
    // Override the makeSound method
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

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

public class Main {
    public static void main(String[] args) {
        // Create Animal objects, but of derived classes
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        // Call the overridden method
        animal1.makeSound(); // Should print "Woof!"
        animal2.makeSound(); // Should print "Meow!"
    }
}

 Output:

Woof!
Meow!

In this program, **Polymorphism** is used so that a variable of type Animal can refer to objects of different derived classes such as Dog and Cat, and call the corresponding overridden methods. This approach makes code more flexible and reusable in object-oriented applications.


 Share this JAVA exercise