실행 가능한 인터페이스에 대해 super를 사용하고 저장하기 위해 Object 유형을 정의하고 있습니다. 컴파일 오류가 발생하지 않지만 아래 코드의 경우 MyRunnale (i)는 MyObject를 사용하여 저장하지만 컴파일러에서 컴파일 오류가 발생합니다. 유형 불일치
컴파일되는 이유를 설명하십시오. 오류 및 왜 거기에 도착하는지.
class Test
{
public static void main(String[] args) {
ArrayList<? super Runnable> a1 = new ArrayList<Object>();
// Here am not getting any CTE but for the below code
ArrayList<? super MyRunnable> a2 = new ArrayList<MyObject>();
// compile error: Type mismatch: cannot convert from ArrayList<MyObject> to
// ArrayList<? super MyRunnable>
}
}
class MyObject {
}
interface MyRunnable {
}
class MyThread extends MyObject implements MyRunnable {
}
를 사용 ArrayList<? super Runnable>
하면 ArrayList가의 ArryList Runnable
및 모든 수퍼 유형 Runnable
(이 경우 ArrayList<Runnable>()
또는 ArrayList<Object>()
)을 참조 할 수 있음을 의미합니다 .
그러나 MyObject
의 하위 유형입니다 Runnable
. 따라서을 할당 할 ArrayList<MyObject>()
수 없습니다.
당신이 참조 할 경우 ArrayList<MyObject>()
, 당신은 사용해야합니다 ArrayList<? extends Runnable>
.
그러나 PECS 규칙 을 충족하는지 확인하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다