java中downcast向下转型到底有什么用

What is the point of downcast? 当一个方法只有子类才有,马克-to-win:不是说基类和子类都有,开始时又是基类指针指向派生类,这时就需要downcast, see the following example. after you cast with SubClass,sc is pure SubClass type.
马克- to-win:马克 java社区:防盗版实名手机尾号: 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: 可以用基类指针调用基类仅有的方法, 但不能调用子类仅有的方法。必须向下强转一下。
        // 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