java 向上轉型與向下轉型
阿新 • • 發佈:2018-01-27
上轉型 post ets public pan lar getname clas ()
向上轉型:子類轉父類
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) { thrownew 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); } }
java 向上轉型與向下轉型