1. 程式人生 > >關於Java繼承的 向上轉型和向下轉型

關於Java繼承的 向上轉型和向下轉型

在Java中, 向上轉型(upcasting)和向下轉型(downcasting)的前提,必須是有“繼承關係”,向上轉型是自動的,向下轉型需要進行強轉。

例如:

/**定義了一個“父”類*/
public class Father {
    /**姓名*/
    private String name;
    /**年齡*/
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this
.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } /**重寫toString 方法*/ public String toString() { return "我叫:" + name + "今年" + age + "歲"; } } /**定義了一個“子”類*/ public class Son extends Father{ /**子類特有的“說你好”方法*/
public void sayHey() { System.out.println("你好"); } } /**程式入口*/ public class Main { public static void main(String [] args) { /**父類引用型變數 father 指向 Son 在堆中new出來的例項*/ Father father = new Son(); //向上轉型(自動) father.setName("小麗"); father.setAge(18); /**輸出資訊*/
System.out.println(father); /**將父類引用型別的變數father 中的地址 賦給 子類引用型別的變數son * 子類引用型別的變數son 指向 子類的例項 */ Son son =(Son) father; //向下轉型(強轉) /**執行子類特有方法*/ son.sayHey(); } }

幾句定義:
1 . 一個基類的引用型別變數可以“指向”其子類的物件
例如上面的:Father father = new Son();

2 . 一個基類的引用不可以訪問其子類物件新增的成員(屬性和方法)
如下:

Father father = new Son(); 

/**
 *父類引用訪問子類特有的sayHey方法;
 * 報錯(The method sayHey() is undefined for the type Father)
 */
father.sayHey();  

如果程式碼較多,不確定引用變數是否屬於該類或該類的子類,可以用instanceonf 判斷 該引用型變數所“指向”的物件是否屬於該類或該類的子類。


    Father father = new Father();
    Father fSon = new Son();
        System.out.println((fSon instanceof Son)? true : false);//輸出true
        System.out.println((father instanceof Son)? true : false);//輸出false

如有錯誤,還請指正,謝謝。