class 层次结构中的向下转换与向上转换
Downcasting versus upcasting within class hierarchy
我有以下代码:
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 ?
}
其中 Grandchild
是 Child
的子项,Child
是 Parent
的子项。
到目前为止,我知道 p=c
是向上转型,而 c = (Child) p;
是合法的向下转型。现在,我的问题是,c = (Grandchild) p;
是什么?
我对如何将 p
一直向下转换为 Grandchild
感到困惑。但是,如果 c
是 Child 类型,如果 Grandchild
class 是 Child
的子类型,那么 c = (Grandchild) p;
不会被视为向上转型吗?
c = (Grandchild) p;
如果 p
实例化为 Child
(如您的示例),将导致 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
实例化为 GrandChild
:
Parent p = new GrandChild();
GrandChild g;
g = (GrandChild)p;
我有以下代码:
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 ?
}
其中 Grandchild
是 Child
的子项,Child
是 Parent
的子项。
到目前为止,我知道 p=c
是向上转型,而 c = (Child) p;
是合法的向下转型。现在,我的问题是,c = (Grandchild) p;
是什么?
我对如何将 p
一直向下转换为 Grandchild
感到困惑。但是,如果 c
是 Child 类型,如果 Grandchild
class 是 Child
的子类型,那么 c = (Grandchild) p;
不会被视为向上转型吗?
c = (Grandchild) p;
如果 p
实例化为 Child
(如您的示例),将导致 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
实例化为 GrandChild
:
Parent p = new GrandChild();
GrandChild g;
g = (GrandChild)p;