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.

luk2302
  • 55,258
  • 23
  • 97
  • 137
sevenxuguang
  • 177
  • 9
  • You should read [What is the difference between a variable, object, and reference?](http://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference). – Sotirios Delimanolis Dec 31 '15 at 18:29

3 Answers3

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();
    }
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
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.

Maxim Votyakov
  • 714
  • 5
  • 10
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?

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129