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

7.5 Type checks and casting — reaching the subclass method

Lesson

Приведение открывает доступ

Knowing that an object is really a Dog is not enough — the variable is still declared Animal. A cast tells the compiler «treat this reference as a Dog», and the subclass methods become available:

Dog d = (Dog) zoo[i];
System.out.println(d.fetch());

Nothing is converted and no new object appears. The object was always a Dog; the cast only changes how the compiler looks at the reference.


Проверять обязательно

Animal x = new Cat("Kit");
Dog d = (Dog) x;   // compiles fine, then crashes:
// ClassCastException: class Cat cannot be cast to class Dog

The compiler allows the cast — it cannot know what will be inside at run time. So the pair is inseparable: check with instanceof, then cast.

if (zoo[i] instanceof Dog) {
    Dog d = (Dog) zoo[i];
    System.out.println(d.fetch());
}

▶ Try it: run this, then change something and run it again.



What does a cast actually do?


Casting a Cat to Dog results in...


Type exactly what this program prints.

class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String describe() {
        return name + " is an animal";
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public String fetch() {
        return getName() + " fetches the ball";
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
}

public class Main { public static void main(String[] a){
    Animal[] zoo = { new Cat("Kit"), new Dog("Rex") };
    for (int i = 0; i < zoo.length; i++) {
        if (zoo[i] instanceof Dog) {
            Dog d = (Dog) zoo[i];
            System.out.println(d.fetch());
        } else {
            System.out.println(zoo[i].describe());
        }
    }
}}

Why check with instanceof before casting?


True or false?