最初に、Java による明示的および暗黙的な型キャストについて読んでください。
そのユーザーから、オブジェクトの関係を絞り込むときに明示的なキャストを行う責任があり、ユーザーはこのために精度が失われることを知っていて問題ありません。ただし、コンパイラは明示的な間違ったキャストを検出CE: Type mismatch error
し、ある時点でスローすることができます。それを超えると、それを処理するのは実行時ClassCastException
になります。
コンパイラは、明示的なキャストの次のケースを検出できます。
class A {}
class B {}
A a = (A) new B(); //CE: Type mismatch: cannot convert from B to A
B b = (B) new A(); //compilation error (CE)
interface I {}
final class A {}
I i = (I) new A(); //compilation error
コンパイラは、明示的なキャストの次のケースを検出できません。
class A {}
class B extends A {}
A a = (A) new B(); //Fine
B b = (B) new A(); //Runtime error; because compile time;
//compiler wont be able to tell the reference is instance of A or B.
//means this is something like below. <BR>
B b = (B) (A) new A();
コンパイル エラーなしで、任意のオブジェクトを任意のインターフェイスにキャストできます。
interface I {}
class A {}
class B extends A implements I{}
I i = (I) new A(); //Runtime error
I i = (I) new B(); //Fine
なぜこれがコンパイルされるのですか?
インターフェイスの参照は、コンパイル エラーなしで任意のオブジェクトにキャストできます。
interface I {}
class A implements I {}
class B {}
B b = (B) getI(); //Runtime error
OR
B b = (B)(I)new A(); //Runtime error
public I getI() {
return new A();
}