+Using Java for these problems+ 1-Write an Animal class that has two member vari
ID: 3883355 • Letter: #
Question
+Using Java for these problems+
1-Write an Animal class that has two member variables called weight and height. It should have two member methods called makeNoise and eat. Both of these methods should only have a print statement saying what that method is. Make the Animals comparable using the weight as the deciding factor of who is bigger. Have setters for both member variables.
2-Write 3 more classes called Dog, Cat and Pig. Each of these classes should have a method calledmakeNoise. The makeNoise of Dog should have a print statement saying Bark. The makeNoise of Cat should have a print statement saying MEOW. The makeNoist of pig should have a print statement saying OUNK.
3-In main class create two objects of type Cat, two objects of type Dog and two objects of type Pig. Set the height and weight of each one as you like. Create an array of type Animal and save all these 6 objects in this array. Name this array arrayA.
4-Write a for loop in main that repeats 6 times and each time call the method makeNoise by having arrayA[i].makeNoise(). You will see that the same line makes different sounds dependingwhat object is stored in that location of the array. We call this Polymorphism. So you havewritten a polymorphic code.
Explanation / Answer
Class Animal implements Comparable<Animal>
{
// Member variables
double weight;
double height;
// Member methods
public void makeNoise()
{
System.out.println(“makeNoise”);
}
public void eat()
{
System.out.println(“eat”);
}
// Setter methods
public void setHeight(double height){
this.height = height;
}
public void setWeight(double weight){
this.weight = weight;
}
// Override the default compareTo method to implement own comparison logic with weight
@Override
public int compareTo(Animal o)
{
if(this.weight < o.weight) return -1;
else if(this.weight == o.weight) return 0;
else return 1;
}
}
// Subclasses of Animal
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.