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.

例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();
    }
}

 

更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44639795/article/details/103117168

posted @ 2021-01-26 20:22  师徒行者  阅读(201)  评论(0编辑  收藏  举报