Create a class Animal and its derived classes Cat, Dog and Duck. The class should include the following methods: Sound( ), Eat( ), Drink( ). Create the objects of all these classes, fill them in an array and randomly select an object from the array and displaying the following information about each object.
A. Name.
B. Breed.
import java.util.Random;
import java.util.Scanner;
class Animal{
public void Sound(){
System.out.print("Animal is sounding");
}
public void Eat(){
System.out.print("Animal is eating");
}
public void Drink(){
System.out.print("Animal is drinking");
}
}
class Cat extends Animal{
String name = "Sofia";
String breed = "Siamese";
@Override
public String toString() {
return "Cat\n" +
"Name: " + name + "\n" +
"Breed: " + breed + "\n";
}
}
class Dog extends Animal{
String name = "Bob";
String breed = "Doberman";
@Override
public String toString() {
return "Dog\n" +
"Name: " + name + "\n" +
"Breed: " + breed + "\n";
}
}
class Duck extends Animal{
String name = "Tom";
String breed = "Beijing";
@Override
public String toString() {
return "Duck\n" +
"Name: " + name + "\n" +
"Breed: " + breed + "\n";
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Object[] arr = new Object[3];
arr[0] = new Cat();;
arr[1] = new Dog();
arr[2] = new Duck();
int y = 0;
Random r = new Random();
do {
int f = r.nextInt(3);
System.out.print(arr[f].toString());
System.out.print("Enter 1 to repeat: ");
y = in.nextInt();
}
while ( y == 1 );
}
}
Comments
Leave a comment