187k views
3 votes
Modify the Java program below to demonstrate Polymophism. Make Animal sound to take different forms for Pig, Dog, Bird, Rat and Lion.

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 Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Sample output:
Demonstration of Polymophism:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
The Bird: Whistle
The Rat: Squeak
The Lion: Roar

User Thodg
by
7.2k points

1 Answer

1 vote

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();

}

}

User Ngnguyen
by
8.6k points