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

WRITE IN JAVA . Assume that the following classes have been created. Do not writ

ID: 3888972 • Letter: W

Question

WRITE IN JAVA .

Assume that the following classes have been created. Do not write any import statements.

An abstract class named Pet. This class has a private String attribute called name that is set by the constructor.

The Pet class also has a public method called getName().

A sub-class of the Pet class named Dog that has a constructor that takes a single String parameter for name. The constructor passes this value upto the super class for initialisation.

The Dog class also has a method called fetch that returns a String value.

A sub-class of the Pet class named Cat that has a constructor that takes a single String parameter for name. The constructor passes this value upto the super class for initialisation.

What you need to do:

1.) Declare and instantiate a single array that can hold both Dog and Cat objects. The size of the array should be 3.

2.) Instantiate a Dog with the name "Fido".

3.) Instantiate an Cat with the name "Toby".

4.) Instantiate a Dog with the name "Henry".

5.) Assign the Dog named Fido to the first position in the array

6.) Assign the Cat named Toby to the second position in the array.

7.) Assign the Dog named Henry to the third position in the array

8.) Write a standard for loop that will iterate through the array.

9.) If a dog object is encountered then it should call the fetch method and print the results of the method call to the console.

10.) If a cat object is encountered then it should call the getName method and print the results of the method call to the console.

Explanation / Answer

abstract class Pet //abstract base class

{

private String name;

public Pet(String name) //argument constructor

{ this.name = name;}

public String getName()

{ return name; }

public abstract String fetch(); //abstract method

}

class Dog extends Pet

{

public Dog(String name)

{ super(name); } // call to base class constructor

  

public String fetch() // implementing base class abstract methos

{

return "Dog";

}

  

}

class Cat extends Pet

{

public Cat(String name)

{ super(name); } // call to base class constructor

  

public String fetch() //implementing base class abstract method

{

return "Cat";

}

  

}

class Test

{

public static void main (String[] args)

{

Pet[] pet = new Pet[3]; //array of 3 objects of class Pet

//initialize objects in array

pet[0] = new Dog("Fido");

pet[1] = new Cat("Toby");

pet[2] = new Dog("Henry");

for(int i = 0;i<3;i++)

{

if(pet[i] instanceof Dog) //instanceof method isused to know the name of class

System.out.println(pet[i].fetch());

else

System.out.println(pet[i].getName());

}

}

}

Output: