java中的多态

多态:
同一个引用类型,使用不同的实例而执行不同操作(父类引用子类对象)
如何实现多态:
1、使用继承
2、子类重写父类的方法
3、父类引用子类
多态的优点:
1、可替换性。多态对已存在的代码具有可替换性
2、可扩充性。多态对代码具有可扩充性。
3、接口性。
4、灵活性。
5、简化性。

下面用一个实例解释多态:
弹奏乐器:乐器主要有钢琴和小提琴两种
共有属性为品牌和重量
都有弹奏的方法,但弹奏的内容不同
乐器Instrument类
public class Instrument {

	protected String brand;//品牌
	protected String weight;//重量
	public Instrument(String brand, String weight) {
		super();
		this.brand = brand;
		this.weight = weight;
	}
	
	public void play(){
		System.out.println("乐器弹奏方法");
	}
}
钢琴Piano类
public class Piano extends Instrument {

	private int size;//尺寸
	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public Piano(String brand, String weight,int size) {
		super(brand, weight);
		// TODO Auto-generated constructor stub
		this.size = size;
	}
	
	@Override
	public void play() {
		// TODO Auto-generated method stub
		System.out.println("*****钢琴*****");
		System.out.println("品牌:"+brand+"\n重量:"+weight+"kg\n尺寸:"+getSize()+"cm");
		System.out.println("钢琴弹奏。。");
	}
}
小提琴Violin类
public class Violin extends Instrument {

	private int length;
	public Violin(String brand, String weight,int length) {
		super(brand, weight);
		// TODO Auto-generated constructor stub
		this.length = length;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}
	
	@Override
	public void play() {
		// TODO Auto-generated method stub
		System.out.println("*****小提琴*****");
		System.out.println("品牌:"+brand+"\n重量:"+weight+"kg\n长度:"+getLength()+"cm");
		System.out.println("小提琴弹奏");
	}
}
测试类
public class Artist {	
	
	public static void make(Instrument instrument){
		System.out.println("演奏家");
		instrument.play();
	}	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Piano pi = new Piano("钢琴品牌", "15.1", 150);
		Violin vi = new Violin("小提琴品牌", "2.1", 50);
		Artist.make(pi);
		Artist.make(vi);
	}
}

执行结果:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值