문제

import java.util.Collection;


public class Test
{
    public static void main(String[] args)
    {
        Collection c = null;
        Test s = null;

        s = (Test) c;
    }
}

위의 코드 샘플에서 테스트 객체에 컬렉션 개체를 캐스팅하고 있습니다. (널 포인터 무시). 테스트가 있습니다 아니요 컬렉션과의 관계는 무엇이든, 그러나이 프로그램은 모든 컴파일 시간 점검을 통과합니다.

왜 이것이 왜 궁금합니다. 내 가정은 인터페이스가 너무 복잡하기 때문에 무시된다는 것입니다. 그들은 공통 수퍼 유형이 없으며 각 클래스는 여러 인터페이스를 구현할 수 있으므로 클래스/인터페이스 계층 구조는 너무 복잡하여 효율적으로 검색 할 수 있습니까?

그 이유 외에 나는 그만큼 혼란스러워한다. 아는 사람 있나요?!

도움이 되었습니까?

해결책

"비정기"는 여기에서 키워드입니다. 다른 수업이있을 수 있습니다

public class Test2 extends Test implements Collection

그의 인스턴스는 결국 할당됩니다 s 캐스트를 완벽하게 합법적으로 만듭니다.

다른 팁

서브 클래스 때문에 Test 잠재적으로 하위 유형이 될 수 있습니다 Collection 또한! 언어 사양은 런타임에 확인할 수있는 캐스트를 허용하기 위해 약간 유연하게 설계되었습니다.

우리는 다른 잠재력에서 볼 수 있습니다. 모든 비 최종 클래스는 모든 인터페이스에 캐스팅 될 수 있습니다.

import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {
        Predicate check;

        try {
            /*It's ok to cast to ANY interface because the Base class is not final.
              Java compiler allows it because some class may extend it 
              and implement the predicate interface. 
              So java compiler can check it only at runtime time not compile time.             
            */
            check = (Predicate)(new Base());

            /*
             Java compiler doesn’t allow it because the BaseFinal is final.
             And it means that no one can extend it and implement interface Predicate. 
             So java compiler can check it at compile time.
            */
            //check = (Predicate)(new BaseFinal()); 
        } catch (ClassCastException e) {
            System.out.println("Class Cast Exception");
        }
        check = (Predicate)(Base)(new Child());
    }    
}
final class BaseFinal {};

class Base {}

class Child extends Base implements Predicate {
    public boolean test(Object t) { return true; }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top