多态通过分离做什么和怎么做,从另一角度将接口和实现分离出来。
向上转型
把某个对象的引用视为对其及类型的引用的做法被称作向上转型
//创建乐器基类
class Instrument{
public void play(Note n){
print("Instrument.play()");
}
}
public class Wind extends Instrument{
public void play(Note n){
print("Wind.play()"+n);
}
}
public class Brass extends Instrument{
public void play(Note n){
print("Brass.play()"+n);
}
}
public class Music{
public static void tune(Instrument i){
i.play()
}
main(String[] args){
Wind w = new Wind();
tune(w) //Wind.play()
}
}Wind 是从Instrument继承的,所以Instrument的接口必定存在Wind中,从Wind向上转型到Instrument会“缩小”接口。
绑定
编译器怎么知道Instrument引用指向的是Wind对象,而不是Brass对象?
方法调用绑定
绑定:将一个方法调用与方法主体关联起来称作绑定。
- 前期绑定:程序执行前进行绑定
- 后期绑定(动态绑定):运行时根据对象的类型进行绑定
Java中除了static和final方法之外,其他所有的方法都是后期绑定
//基类
public class Shape{
public void draw(){
}
public void erase(){
}
}
public class Circle extends Shape{
public void draw(){
print("Circle draw");
}
public void erase(){
print("Circle erase");
}
}
public class Square extends Shape{
public void draw(){
print("Square draw");
}
public void erase(){
print("Square erase");
}
}
public class Triangle extends Shape{
public void draw(){
print("Triangle draw");
}
public void erase(){
print("Triangle erase");
}
}
public class RandomShape{
}