码迷,mamicode.com
首页 > 其他好文 > 详细

对象向上、向下转型

时间:2015-05-31 23:01:49      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

向上转型(Son-->Father),程序会自动完成

父类 父类对象 = 子类实例

向下转型(Father-->Son),强制类型转换

子类 子类对象 = (子类)父类实例

class Father {

    public void tell() {
        System.out.println("Father tell");
    }
}

class Son extends Father {

    public void tell() {
        System.out.println("Son tell");
    }
}
public class Demo {
    public static void main(String args[]) {
        //向下转型
        Father father = new Son();
        father.tell();
        //向上转型(向上转型时要先进行向下转型)
        Father father = new Son();
        Son son = (Son) father;
        son.tell();

    }
}

 

对象向上、向下转型

标签:

原文地址:http://www.cnblogs.com/sflik/p/4542870.html

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