Java 禁止从实例转换到接口?

Java 禁止从实例转换到接口?,java,android,interface,casting,Java,Android,Interface,Casting,非常简单的测试代码: interface Base { void interfaceTest(); static final String m = "1"; } interface Child extends Base { void interfaceTestChild(); } class BaseClass implements Base { @Override public void interfaceTest() { Syste

非常简单的测试代码:

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();
    }
}
EditText
的超类是
TextView
,其中
getText()
方法是:

public CharSequence getText() {
    return mText;
}
mText是一个
CharSequence
,请注意,Editable扩展了CharSequence,因此您可以看到,这些android代码将
CharSequence
转换为
Editable
,就像我一样,将
Base
转换为
Child
,有什么区别吗

在返回(子)x行中;我得到了一个“ClassCastException”,对此我感到非常困惑,因为Child扩展了Base,所以x应该成功地转换为Child

不,只有当
x
*实际引用了实现
Child
的某种类型的实例时,它才会起作用。在本例中,它不是-它只引用
基类的一个实例。这并没有为
interfaceTestChild()
指定任何行为,所以如果能够调用它,会发生什么

Base x = new BaseClass();
// Imagine this had worked...
Child child = (Child)x;
// What would this do? There's no implementation!
child.interfaceTestChild();
Java只允许您强制转换到该值实际支持的类型,即该值所引用的对象继承层次结构中的某个类型

在返回(子)x行中;我得到了一个“ClassCastException”,对此我感到非常困惑,因为Child扩展了Base,所以x应该成功地转换为Child

不,只有当
x
*实际引用了实现
Child
的某种类型的实例时,它才会起作用。在本例中,它不是-它只引用
基类的一个实例。这并没有为
interfaceTestChild()
指定任何行为,所以如果能够调用它,会发生什么

Base x = new BaseClass();
// Imagine this had worked...
Child child = (Child)x;
// What would this do? There's no implementation!
child.interfaceTestChild();
Java只允许您强制转换到该值实际支持的类型,即该值所引用的对象继承层次结构中的某个类型