Search code examples
javainterfacebooleaninstanceof

Java Instanceof method Confusion


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.


Solution

  • 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();
        }
    }