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是一个法律上的负面因素。现在,我的问题是,什么是
c=(孙子)p?
我很困惑,我们怎么能把
p
一直往下推到
孙子
。然而,如果
c
是Child类型,则不会
c=(孙子)p孙子类
子类
的子类型,则code>将被视为向上投射

c=(孙子)pp
实例化为
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;

它将编译而不出错,但会在运行时引发异常