0

Can anyone explain the following behavior in Java using instanceof operator .

Runnable r = new Thread();

eventhough the type of variable r is Runnable and the instanceof comparison is done on classes that do not reside in the same class hierarchy

System.out.println(r instanceof String); // This line does not compile 

System.out.println(r instanceof Vector); // This line compiles

System.out.println(r instanceof FileNotFoundException); // This line compiles
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
redeemed
  • 471
  • 7
  • 22

3 Answers3

3

String class is final -- that means it can't be subclassed. Moreover, it doesn't implement Runnable. All of this is known at compile time; hence, compilation error.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
1

An example:

static class First {

}

static final class Second {

}

And than :

    Runnable r = new Thread();

    System.out.println(r instanceof First);

    System.out.println(r instanceof Second);

The compiler sees that Second is final, thus it can not have any sub-classes, thus it can not implement Runnable.

Eugene
  • 117,005
  • 15
  • 201
  • 306
0

The String class is final and it doesn't implement the Runnable interface. Hence, r instanceof String can never return true (since there cannot be any sub-class of String that would implement Runnable), which is why the compiler doesn't allow it.

On the other hand, there may be sub-classes of the Vector class or the FileNotFoundException class that implement the Runnable interface, so r instanceof Vector and r instanceof FileNotFoundException may return true as far as the compiler can tell.

This is covered by JLS 15.20.2:

If a cast (ยง15.16) 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. In such a situation, the result of the instanceof expression could never be true.

Eran
  • 387,369
  • 54
  • 702
  • 768