Answer to Question #314111 in Java | JSP | JSF for superBoy

Question #314111

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.


1
Expert's answer
2022-03-18T15:51:22-0400
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 );

    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS