Search code examples
javainstanceof

instanceof with custom/core classes


Why can I test my custom class against my custom interface using instanceof and I am unable to do the same with java core classes?

interface A{}
class B{}
public class Tmp {
    public static void main(String [] args) {
        String s = "";
        Integer i = 1;
        B b = new B();
        System.out.println(s instanceof A); //1
        System.out.println(i instanceof A); //2
        System.out.println(b instanceof A); //3
    }
}

Lines 1 and 2 won't compile. Line 3 will compile (and print false). What's the difference?


Solution

  • If the compiler can detect that the instanceof operation could never be true it will generate a compiler error. It determines this by following the same rules as that for casting. The specific rule is described in Section 15.20.2 of the JLS:

    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. In such a situation, the result of the instanceof expression could never be true.