rtgher
rtgher

Reputation: 159

Does casting affect result of instanceof operation?

I'm confused.

Say we have the following classes:

class Shape { /* ... */ }
class Square extends Shape { /* ... */ }

what are the resulting booleans, and why are they so?

Shape shape = ...;
boolean b1 = shape instanceof Square;

Square square = ...;
boolean b2 = ((Shape) square) instanceof Square;

boolean b3 = shape instanceof Object;

From what I know, a subclass is an instance of a parent, but not the other way around?

Upvotes: 2

Views: 1148

Answers (2)

Andy Turner
Andy Turner

Reputation: 140318

Refer to the language spec:

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

So instanceof is unaffected by casts: it's checking if the runtime value can be cast; the runtime value itself is unaffected by a cast, all it does is to tell the compiler to "trust you" that the type conversion is safe.

So, the three booleans are:

  • b1:
    • false if you assigned shape = null;
    • true if you assigned shape = new Square();
    • false if you assigned shape = new Shape();, or any other subclass of Shape.
  • b2:
    • false if you assigned square = null;
    • true otherwise, as the cast doesn't create a "new" Shape.
  • b3:
    • false if you assigned shape = null;
    • true otherwise, as every non-null instance of a reference type can be cast to an Object/assigned to a variable of type Object.

Upvotes: 2

rom1v
rom1v

Reputation: 2969

In this code:

Number n = new Integer(42);

Number is the apparent type of n, while Integer is its real type.

Casts change the apparent type, while instanceof checks against the real type.

As a consequence, casting has no effect on instanceof results.

Upvotes: 8

Related Questions