java中downcast向下轉(zhuǎn)型到底有什么用

What is the point of downcast? 當(dāng)一個方法只有子類才有,馬克-to-win:不是說基類和子類都有,開始時又是基類指針指向派生類,這時就需要downcast, see the following example. after you cast with SubClass,sc is pure SubClass type.
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。



例1.9.1---本章源碼 

class SuperClassM_t_w {
    int a;
    SuperClassM_t_w() {
        a = 5;
    }
    public void printAsuper() {
        System.out.println("父類中a =" + a);
    }
}

class SubClass extends SuperClassM_t_w {
    int a;
    SubClass(int a) {
        this.a = a;
    }
    public void printA() {
        System.out.println("子類中a = " + a);
    }
}
public class Test {
    public static void main(String args[]) {
/* note that new SubClass(10) will call SuperClassM_t_w(), default constructor. */
        SuperClassM_t_w s1 = new SubClass(10);
        s1.printAsuper();//基類指針指向派生類時,馬克-to-win: 可以用基類指針調(diào)用基類僅有的方法, 但不能調(diào)用子類僅有的方法。必須向下強轉(zhuǎn)一下。
        // s1.printA();錯誤
/* 我們不能去掉下面的話,因為SuperClassM_t_w沒有printA方法。馬 克-to-wi n:we can not comment the following statement,because SuperClassM_t_w does not have the method of printA, report error */
        SubClass sc = (SubClass) s1;
        sc.printA();
    }
}

 

the result is:

父類中a =5
子類中a = 10