- 程序中的多态:同一个引用类型,使用不同的实例而执行不同的操作;父类引用子类对象
- 子类重写了父类的方法
- 父类引用子类对象
使用继承
- 实例:让一个乐器家弹多种乐器:
父类:public abstract class Instrument {
public abstract void play();
}
子类1:public class Piano extends Instrument{
public void play() {
// TODO Auto-generated method stub
System.out.println(“月光曲”);
}}
子类2:public class Violin extends Instrument{
public void play() {
System.out.println(“我在贵州等你”);
}}用乐器的人:public class Artist {
//向上转型
public void make(Instrument instrument) {
instrument.play();
}
}测试:public class Test {
public static void main(String[] args) {
Artist artist=new Artist();
Piano piano=new Piano();
artist.make(piano);
Violin violin=new Violin();
artist.make(violin);
}
- 像上面这样就使用了多态,通过定义父类来访问子类的方法
面向对象的基本步骤
继承可以做到代码的重用
- 抽象类不能被实例化,抽象方法必须被子类重写
- 多态要有继承;