Final answer:
Polymorphism is a concept in object-oriented programming where a subclass can be treated as its superclass. In the given Java program, we can demonstrate polymorphism by creating objects of the Animal class and its subclassesand invoking the animalSound() method on each of them.
Step-by-step explanation:
Polymorphism is a concept in object-oriented programming where a subclass can be treated as its superclass. In the given Java program, we can demonstrate polymorphism by creating objects of the Animal class and its subclasses (Pig and Dog) and invoking the animalSound() method on each of them.
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
class Bird extends Animal {
public void animalSound() {
System.out.println("The Bird: Whistle");
}
}
class Rat extends Animal {
public void animalSound() {
System.out.println("The Rat: Squeak");
}
}
class Lion extends Animal {
public void animalSound() {
System.out.println("The Lion: Roar");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
Animal myBird = new Bird(); // Create a Bird object
Animal myRat = new Rat(); // Create a Rat object
Animal myLion = new Lion(); // Create a Lion object
System.out.println("Demonstration of Polymorphism:");
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
myBird.animalSound();
myRat.animalSound();
myLion.animalSound();
}
}