java中的多态

来源:互联网 发布:国内云计算排名 编辑:程序博客网 时间:2024/06/05 17:56
多态:
同一个引用类型,使用不同的实例而执行不同操作(父类引用子类对象)
如何实现多态:
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 stubthis.size = size;}@Overridepublic void play() {// TODO Auto-generated method stubSystem.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 stubthis.length = length;}public int getLength() {return length;}public void setLength(int length) {this.length = length;}@Overridepublic void play() {// TODO Auto-generated method stubSystem.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 stubPiano pi = new Piano("钢琴品牌", "15.1", 150);Violin vi = new Violin("小提琴品牌", "2.1", 50);Artist.make(pi);Artist.make(vi);}}

执行结果:


原创粉丝点击