IT박스

'instanceof'연산자는 인터페이스와 클래스에 대해 다르게 작동합니다.

itboxs 2020. 9. 10. 07:32
반응형

'instanceof'연산자는 인터페이스와 클래스에 대해 다르게 작동합니다.


instanceofJava에서 연산자의 다음 동작에 대해 알고 싶습니다 .

interface C {}

class B {}

public class A {
    public static void main(String args[]) {
        B obj = new B();
        System.out.println(obj instanceof A);      //Gives compiler error
        System.out.println(obj instanceof C);      //Gives false as output
    }
}

왜 그래야만하지? 이 사이에 아무 관계 없다 interface C하고 class B, 그러나의 그것은 경우에 반면 거짓 제공 obj instanceof A은 컴파일러 오류를 준다?


Java에는 다중 클래스 상속이 없기 때문에 컴파일 중에 obj유형의 객체가의 B하위 유형이 될 수 없다는 것이 절대적으로 알려져 있습니다 A. 반면에 다음과 같이 interface의 하위 유형이 될 수 있습니다 C.

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  
    }
}

따라서 obj instanceof C표현식 컴파일러 만 보면 그것이 참인지 거짓인지 미리 알 수 없지만, obj instanceof A그것을 보면 이것이 항상 거짓이라는 것을 알고 있으므로 의미가 없으며 오류를 방지하는 데 도움이됩니다. 프로그램에서이 의미없는 검사를 계속하려면에 명시 적 캐스팅을 추가 할 수 있습니다 Object.

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

final아래 클래스 선언에서 한정자 를 사용 Test하면 인터페이스를 구현할 수있는의 하위 클래스가있을 수 없음을 보장합니다 Foobar. 이 경우 TestFoobar서로 호환되지 않음 이 분명합니다 .

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 {
}

그렇지 Test않고 선언되지 않은 경우 final의 서브 클래스가 Test인터페이스 구현할 수 있습니다. 이것이 컴파일러 test instanceof Foobar가이 경우 명령문 허용하는 이유 입니다.

참고 URL : https://stackoverflow.com/questions/31398444/the-instanceof-operator-behaves-differently-for-interfaces-and-classes

반응형