The 'instanceof' operator behaves differently for interfaces and classes

前端 未结 2 1791
天涯浪人
天涯浪人 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:22

    By using the final modifier in the class declaration below, it is guaranteed that there couldn't be a subclass of Test, which may implement the interface Foobar. In this case, it is obvious that Test and Foobar are not compatible with each other:

    public final class Test {
    
        public static void main(String[] args) {
            Test test = new Test();
            System.out.println(test instanceof Foobar); // Compiler error: incompatible types
        }
    }
    
    interface Foobar {
    }
    

    Otherwise, if Test is not declared final, it might be possible that a subclass of Test implements the interface. And that's why the compiler would allow the statement test instanceof Foobar in this case.

提交回复
热议问题