java中子类转父类和父类转子类

前提概要

已经有父类和子类如下所示:

// 父类
public class Parent {}

// 子类
public class Son extends Parent {}

// 女儿类
public class Daughter extends Parent {}

子类转父类

子类的引用指向子类转父类对象

Son son = new Son();
Parent parent = (Parent) son;

结果

运行没问题

父类的引用指向子类转父类对象

Parent son = new Son();
Parent parent = (Parent) son;

结果

运行没问题,这种肯定也是可以的

父类转子类

父类的引用指向父类转子类对象

Parent parent = new Parent();
Son son = (Son) parent;

结果

运行有问题会报 ClassCastException

父类的引用指向子类转子类对象

Parent parent = new Son();
Son son = (Son) parent;

结果

运行没有问题

父类的引用指向子类转另一个子类对象

Parent parent = new Son();
Daughter daughter = (Daughter) parent;

结果

运行时报出 ClassCastException 的异常

猜你喜欢

转载自blog.csdn.net/abcnull/article/details/107747450
今日推荐