非常に簡単なコード:行return (Child)x;
でインスタンスからインターフェイスへのキャストは禁止されていますか?テストのための
interface Base {
void interfaceTest();
static final String m = "1";
}
interface Child extends Base {
void interfaceTestChild();
}
class BaseClass implements Base {
@Override
public void interfaceTest() {
System.out.println("BaseClassInterfaceTest");
}
}
class ChildClass implements Child {
@Override
public void interfaceTest() {
System.out.println("ChildClassInterfaceTest");
}
@Override
public void interfaceTestChild() {
System.out.println("interfaceTestChild");
}
}
public class Src {
public Child testFunc() {
Base x = new BaseClass();
return (Child)x; <==Here got an "ClassCastException"
}
public static void main(String args[]) {
Src testSrcInstance = new Src();
testSrcInstance.testFunc().interfaceTest();
}
}
私は「ClassCastExceptionが」持って、Child
はBase
を拡張し、そうx
が正常にChild
に変換する必要があるため、私は、それについて非常に混乱を感じます。会話のこの種は、いくつかのAndroidコードで模倣される:EditText
の
getText()
方法は次のとおりです。
public Editable getText() {
return (Editable) super.getText();
}
とEditText
のスーパークラスはTextView
あり、getText()
方法があるの:
public CharSequence getText() {
return mText;
}
mTextはCharSequence
であり、CharSequenceを拡張できることに注意してください。これらのアンドロイドコードはCharSequence
からにキャストされています、ちょうど私と同じキャストBase
〜Child
、違いはありますか?