前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >继承的特点、多态,

继承的特点、多态,

作者头像
HaC
发布2020-12-30 17:35:39
5520
发布2020-12-30 17:35:39
举报
文章被收录于专栏:HaC的技术专栏
代码语言:javascript
复制
package sonandfather;
class father{
    void eat(){
        System.out.println("father eat");
    }
    void hitson(){
        System.out.println("father hit son");
    }
}
class sonXiaoming extends father{
    void eat(){
        System.out.println("sonXiaoming eat");
    }
    void play(){
        System.out.println("sonXiaoming play");
    }
}
class sonXiaogang extends father{
    void eat(){
        System.out.println("sonXiaogang eat");
    }
    void sing(){
        System.out.println("sonXiaogang sing");
    }
}
public class SonextendsFather {
    public static void main(String args[]) {
        father f=new sonXiaoming(); //父类类型引用子类对象,向上转型。
        f.eat();   //调用的是子类的方法,规则是先从子类找该方法,找不到先父类找
        f.hitson();//子类无该方法,向父类找
    //  f.play(); 报错,父类f无该方法
        father f1=new father();
        f1.eat();  //父类对象调用父类方法
        f1.hitson();
        sonXiaoming xm=new sonXiaoming();
        xm.eat();
        xm.play();
        father fa=new sonXiaoming();
        method(fa);
        method(new father());
        method(new sonXiaoming());
        method(new sonXiaogang());
    }
    public static void method(father f) {
        if(f instanceof sonXiaoming){
            sonXiaoming xm=(sonXiaoming)f; //向下转型
            xm.play();      
        }
        if(f instanceof sonXiaogang){
            sonXiaogang xg=(sonXiaogang)f; //向下转型
            xg.sing();
        }
    }
}

控制台输出:

代码语言:javascript
复制
sonXiaoming eat
father hit son
father eat
father hit son
sonXiaoming eat
sonXiaoming play
sonXiaoming play
sonXiaoming play
sonXiaogang sing

涉及到了多态

多态在代码中的体现: 父类或者接口的引用指向其子类的对象。 多态的条件: 1.有联系继承、实现。 2.方法必须覆盖。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/02/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 涉及到了多态
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档