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:
- Create a base class named
Animal
with a makeSound()
method that prints a generic sound.
- 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.
- 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.
View Example Code
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.