Task 1 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 — asking what an object is

Lesson

Проблема, которую оставил полиморфизм

An Animal[] can hold dogs and cats, and calling describe() works on all of them. But Dog has fetch(), which Animal does not — and through an Animal variable that method is invisible:

Animal x = new Dog("Rex");
x.fetch();   // error: cannot find symbol

The compiler goes by the declared type, not by what is actually inside. It sees an Animal, and Animals do not fetch.


instanceof — вопрос о настоящем типе

System.out.println(zoo[i] instanceof Dog);   // true for a Dog, false for a Cat

It answers «is the object really of this type?» and returns a plain boolean. It is safe on any reference: for null it simply gives false, never a crash.

This is the tool for the moments when uniform treatment is not enough and you need to single out one kind of object.


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



instanceof returns...


Why can you not call fetch() through an Animal variable?


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 x = new Cat("Kit");
    System.out.println(x instanceof Cat);
    System.out.println(x instanceof Dog);
    System.out.println(x instanceof Animal);
}}

null instanceof Dog gives...


True or false?