向上转型:子类转父类
Father father1= new Son();
向下转型:父类转子类
Son son = (Son)new Father (); // 这样是运行时会报错
Father father1 = new Son(); Son son1 = (Son) father1; // 这样不报错
通过写一个方法把父类转换为子类
class Father { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 将当前对象转换为子类对象 * * @param clazz 目标类型 * @return 目标对象 */ public <T extends Father> T to(Class<T> clazz) { T instance; try { instance = clazz.newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Failed to create " + clazz.getSimpleName() + " instance.", e); } instance.setName(this.getName()); return instance; } }
public class Son extends Father { private String age; public String getAge() { return age; } public void setAge(String age) { this.age = age; } public static void main(String[] args) { // 子类转父类,父类再转子类 // Father father = new Son(); // Son son = (Son) father; // 父类直接转子类 // Son son = (Son)new Father (); // 运行时会报错 // 父类通过方法转直接转子类 Father father = new Father(); Son son = father.to(Son.class); } }