Java 类层次结构中的向下投射与向上投射
我有以下代码:Java 类层次结构中的向下投射与向上投射,java,inheritance,casting,Java,Inheritance,Casting,我有以下代码: public static void main (String[] args) { Parent p = new Child(); Child c = null; Grandchild g = null; p = c; // upcast c = (Child) p; // downcast c = (Grandchild) p; // downcast ? } 其中,孙子女是子子女的子子女是父子女的子子女 我知道p=c是一
public static void main (String[] args) {
Parent p = new Child();
Child c = null;
Grandchild g = null;
p = c; // upcast
c = (Child) p; // downcast
c = (Grandchild) p; // downcast ?
}
其中,孙子女
是子子女
的子子女是父子女
的子子女
我知道p=c
是一个向上投射,而c=(Child)p到目前为止,code>是一个法律上的负面因素。现在,我的问题是,什么是c=(孙子)p代码>?
我很困惑,我们怎么能把p
一直往下推到孙子
。然而,如果c
是Child类型,则不会c=(孙子)p如果孙子类
是子类
的子类型,则code>将被视为向上投射 c=(孙子)p如果将p
实例化为Child
(如您的示例所示),则code>将导致ClassCastException
。因此,这既不是一个演员阵容,也不是一个沮丧的人。例如:
Parent p = new Child();
GrandChild g;
g = (GrandChild)p;
将导致
Exception in thread "main" java.lang.ClassCastException: test.Child cannot be cast to test.GrandChild
at test.Test.main(Test.java:18)
Java Result: 1
要使其有效,您必须将p
实例化为孙辈
:
Parent p = new GrandChild();
GrandChild g;
g = (GrandChild)p;
它将编译而不出错,但会在运行时引发异常