1

Suppose we have the following definition.

interface Vessel{}
interface Toy{}
class Boat implements Vessel{}
class Speedboat extends Boat implements Toy{}

In main, we have these:

Boat b = new Speedboat();

and (b instanceof Toy) evaluates to be true? Why? My understanding is that the reference type of b is Boat, but Boat has nothing to do with Toy, so it should be false but the answer is true.

1

3 Answers 3

7

Boat has nothing to with Toy, you are right.

But you are not handling a Boat here but an actual SpeedBoat which is stored in a Boat variable. And that SpeedBoat is an instance of Toy.

The type in which you store the new Speedboat() does not matter since Java checks at runtime wether or not the actual objects is an instance of something else.

That way you can write something like

public boolean callSpeedBoatMethodIfPossible(Boat b) {
    if (b instanceof SpeedBoat) {
        ((SpeedBoat)b).driveVerySpeedy();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

According to http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

So it checks a type of an OBJECT but not a type of REFERENCE to the object.

Comments

2

Compile type of b is Boat. But its run-time type is Speedboat.

What is the difference between a compile time type vs run time type for any object in Java?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.