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);}}
执行结果:
阅读全文
0 0
- Java 中的多态
- java中的多态
- java中的多态
- Java中的多态
- Java中的多态
- Java中的多态
- Java 中的多态
- java中的多态
- java中的多态
- Java中的多态
- Java 中的多态
- Java中的多态
- Java中的多态
- java中的多态
- Java中的多态
- java中的多态
- java中的多态
- Java中的多态
- Cordova+Angularjs+Ionic混合开发入门篇(四)—— 插件的简单使用
- 大数据学习1:大数据平台基础环境搭建:vm虚机搭建+网络调试+克隆+本地yum配置
- PropertyAnimation属性动画
- linux下搭建ftp服务器
- kafka 高级API和低级API
- java中的多态
- 常见的两列布局和三列布局
- nginx搭建前后端分离架构
- jqgrid基本操作(转载)
- search by boshi考试总结
- JVM结构、GC工作机制详解
- JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8: illegal continuation byte 0x3f
- Mysql利用游标遍历查询结果集
- 【排序算法】:九大排序算法总结