继承关系图
父类
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...