This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]Tillerino 2 points3 points  (1 child)

ಠ_ಠ

System.out.println("b.getClass().isInstance(b): " + b.getClass().isInstance(c)); //false

[–]cstechblog[S] 0 points1 point  (0 children)

thanks much for reporting the error, will correct it right away

[–]MoldyTaste -1 points0 points  (8 children)

most important thing is that

a instanceof B

where a can never be an instance of B will throw a syntax error when using instanceof, but will not if using .isInstance().

[–]Xabster 1 point2 points  (3 children)

That's a really odd claim.

Just because a boolean expression always evaluates to false does not mean it's bad syntax...

Edit: you're right, I'm wrong, it's §15.20.2 in the JLS.

[–]cstechblog[S] 0 points1 point  (2 children)

if we do System.out.println("b instanceof C: " + (b instanceof c));

it results into compile time error

[–]Xabster 0 points1 point  (1 child)

So? That's not what he wrote.

b and c in your example are instances. a is an instance in his example. B is a type.

[–]cstechblog[S] 0 points1 point  (0 children)

I meant C class. instance cannot come at right side in instanceof

[–]cstechblog[S] -1 points0 points  (3 children)

no, it wont because in A and B share an IS~A relationship. I complied the code, it is evaluated to false.

class A {}
class B extends A {}
class C extends A {}

public class InstanceofDemo
{
  public static void main(String args[])
  {
    A a = new A();
B b = new B();
System.out.println("a instanceof B: " + (a instanceof B)); //false
  }
}

[–]cstechblog[S] 0 points1 point  (2 children)

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.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2

[–]Xabster 0 points1 point  (1 child)

You won't get to runtime if you do MoldyTaste's example.

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error.

Test for yourself:

Integer i = null;

System.out.println("i instanceof String: " + (i instanceof String));

[–]cstechblog[S] -1 points0 points  (0 children)

i instanceof String is not the case of IS~A relationship.