Question: import java.util. * ; / / for ArrayList public class Pet { private String name; private String type; public Pet ( String n , String

import java.util.*; // for ArrayList
public class Pet
{
private String name;
private String type;
public Pet(String n, String t)
{
name = n;
type = t;
}
public String toString()
{
return name +" is a "+ type;
}
public static void main(String[] args)
{
ArrayList petList = new ArrayList();
petList.add(new Pet("Sammy", "hamster"));
petList.add(new Dog("Fido"));
// This loop will work for all subclasses of Pet
for (Pet p : petList)
{
System.out.println(p);
}
}
}
class Dog extends Pet
{
public Dog(String n)
{
super(n, "dog");
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!