Very simple code for test:
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();
}
}
In the line return (Child)x; I got a “ClassCastException” and I feel very confused about it, for Child extends Base, so x should be converted to Child successfully. this kind of conversation is imitated by some android codes:
the getText() method of EditText is:
public Editable getText() {
return (Editable) super.getText();
}
and the super class of EditText is TextView, of which the getText() method is:
public CharSequence getText() {
return mText;
}
mText is a CharSequence, and note that Editable extends CharSequence, so you can see, these android codes cast CharSequence to Editable, just as me, cast Base to Child, any difference?
No, it will only work if
x*actually refers to an instance of some type which implementsChild. In this case, it doesn’t – it only refers to an instance ofBaseClass. That doesn’t specify any behaviour forinterfaceTestChild(), so what would expect to happen if you’d been able to call it?Java only lets you cast to a type which the value actually supports – i.e. some type in the inheritance hierarchy of the object that the value refers to.