The 'instanceof' operator behaves differently for interfaces and classes

前端 未结 2 1794
天涯浪人
天涯浪人 2020-12-05 01:55

I would like to know regarding following behavior of instanceof operator in Java.

interface C {}

class B {}

public class A {
    public static         


        
2条回答
  •  星月不相逢
    2020-12-05 02:03

    Because Java has no multiple class inheritance it's absolutely known during the compilation that obj object of type B cannot be subtype of A. On the other hand it possibly can be subtype of interface C, for example in this case:

    interface C {}
    
    class B {}
    
    class D extends B implements C {}
    
    public class A {
        public static void main(String args[]) {
            B obj = new D();
            System.out.println(obj instanceof C);      //compiles and gives true as output  
        }
    }
    

    So looking only at obj instanceof C expression compiler cannot tell in advance whether it will be true or false, but looking at obj instanceof A it knows that this is always false, thus meaningless and helps you to prevent an error. If you still want to have this meaningless check in your program, you can add an explicit casting to the Object:

    System.out.println(((Object)obj) instanceof A);      //compiles fine
    

提交回复
热议问题