Java重写,重载,多态

继承关系图

父类

package com.lyw.main2;

public class Instrument {
    String name;
    String type;
    public Instrument(String name) { //父类构造方法
        this.name = name;
    }
    public Instrument(String name, String type) { //相同方法名同一个类进行重载参数列表
        this.name = name;
        this.type = type;
    }
    public void play() { //用子类去重写父类方法名必须相同
        System.out.println(name+"Instrument is playing...");
    }
}

子类

package com.lyw.main2;

public class Wind extends Instrument{
    public Wind(String name,String type) { //重写必须继承方法名必须相同
        super(name,type);
    }
    public void play() {
        System.out.println(name + " is playing..."+type); //重写方法体
    }
}

子类

package com.lyw.main2;

public class Per extends Instrument{
    public Per(String name) { //重载参数列表
        super(name);
    }

    public void play() { //重写必须继承方法名必须相同
        System.out.println(name+" is playing..."); //重写方法体
    }
}

启动类

package com.lyw.main2;

import java.util.ArrayList;
import java.util.List;

public class InstrumentMain {
    public static void main(String[] args) {
        //多态:多态体现为父类引用变量可以指向子类对象,必须有子父类关系
        //在使用多态后的父类引用变量调用方法时,会调用子类重写后的方法。
        //定义格式:父类类型 变量名=new 子类类型();  Instrument instrument = new Wind("风","大自然");
        //意思是一个父类可以有多个子类方法,但是一个子类不能有两,及以上个父
        List<Instrument> instruments = new ArrayList<>();
        instruments.add(new Instrument("乐器"));
        instruments.add(new Wind("风","大自然"));
        instruments.add(new Per("拍打"));
        for(Instrument instrument : instruments){
            instrument.play();
        }
    }
}

运行结果

乐器Instrument is playing...
风 is playing...大自然
拍打 is playing...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YavR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值