Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

. Explain why the call to the equals method does not output an (a) Consider the

ID: 3708794 • Letter: #

Question

. Explain why the call to the equals method does not output an (a) Consider the following main method error even though the class Animal does have an equals method 5. public static void main(String[] args) Animal a new Animal("cow", "moo"); Animal b - new Animal("fish", "glup-glup"); System.out.println(a.equals(b)); a-b; System.out.printinía.equals(b): (b) What will the main above output? (c) Override the equals method in Animal so that the following code would return true: public static void main(String[] args)( Animal a new Animal("frog", "ribbit-ribbit"); Animal b new Animal("frog", "thump-thump); System.out.println(a.equals(b));

Explanation / Answer

5(a)

In java, the Object class is the parent class of all the classes and equals is the method of Object class and hence even if Animal class doesn't have an equals method, it doesn't result into an error as it uses the equals method of its parent class i.e Object..

(b)

public static void main(String[] args)

{

Animal a = new Animal("cow","moo");

Animal b = new Animal("fish","glup-glup");

System.out.println(a.equals(b)); // this will output false since a and b refers to two different objects

a=b; // set a=b

System.out.println(a.equals(b)); // this will output true since both a and b refers to the same object

}

Output:

false

true

(c)

// Updated Animal class

public class Animal {

      

       private static int numAnimals;

       protected String name;

       protected String sound;

      

       public Animal(String n, String s)

       {

             name = n;

             sound = s;

             numAnimals++;

       }

      

       public void breathe()

       {

             System.out.println(name + "is taking a breath");

       }

      

       public Animal eat(Animal a)

       {

             System.out.println("Animal "+name+" is eating animal : "+a.name);

            

             return new Animal1("DeadAnimal",null);

       }

      

       public String getName()

       {

             return name;

       }

      

       public String getSound()

       {

             return sound;

       }

      

       public static int getNumAnimals()

       {

             return numAnimals;

       }

// check if both the animals are equal based on the name of the animal

       public boolean equals(Animal a)

       {

             if(name.equalsIgnoreCase(a.name))

                    return true;

             return false;

       }

}