Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.4 Polymorphism — an array of a superclass type

Lesson

A mixed collection, one loop

Because a superclass variable can hold any subclass object, an array of the superclass type can hold a mix of subclasses: Animal[] zoo = { new Dog(...), new Cat(...) };. Loop over it and call the same method — each element responds with its own version. One loop, many behaviors.


Worked example

Animal[] animals = { new Dog("Rex"), new Cat("Felix"), new Animal("Thing") };
for (int i = 0; i < animals.length; i++) {
    System.out.println(animals[i].describe());
}
// Rex is a dog
// Felix is a cat
// Thing is an animal

The same describe() call gives a different answer for each object.


▶ Try it: run this — one loop makes each animal describe itself in its own way.



An Animal[] array can hold...


Looping over an Animal[] of a Dog and a Cat and calling describe() gives...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String describe(){return n+" is an animal";} }
class Dog extends Animal { Dog(String x){super(x);} String describe(){return n+" is a dog";} }
class Cat extends Animal { Cat(String x){super(x);} String describe(){return n+" is a cat";} }
public class Main { public static void main(String[] a){
    Animal[] arr = { new Dog("Rex"), new Cat("Mia") };
    for (int i = 0; i < arr.length; i++) System.out.println(arr[i].describe());
}}

Storing different subclasses in one superclass array lets you...


True or false?