码迷,mamicode.com
首页 > 编程语言 > 详细

java中downcast向下转型到底有什么用? 举例说明!

时间:2018-09-23 20:46:39      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:state   需要   get   wing   www   htm   following   方法   targe   

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;

。。。。。。。。。。。。。。。。。。。
详情请见:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner3_web.html#PointDowncast

java中downcast向下转型到底有什么用? 举例说明!

标签:state   需要   get   wing   www   htm   following   方法   targe   

原文地址:https://www.cnblogs.com/mark-to-win/p/9693494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!