(一)父类引用指向子类对象
public class Water {
public void flow(int year) {
System.out.println("I can flow" + i + "years");
}
public void dream() {
System.out,println("I am still water");
}
}
public class River extends Water() {
public void flow(int year) {
System.out,println("I can gallop" + i + "years");
}
public void dream(String str) {
System.out,println(str);
}
}
Water water = new River();
water.flow(3);
Result: I can gallop 3 years
解释:对象water先到类Water中寻找flow方法,存在,但由于子类River中重写了该方法,因此调用的是子类中的flow。这就是动态绑定。
另外,water.dream("River is running")是错误的,即父类引用不能调用父类中没有而子类中有的方法。
water.dream()将打印I am still water.
总结:父类引用指向子类对象主要的作用是利用子类中重写父类的方法。
(二)多态时方法调用原则
class College {
public void show(QiluSoftware o) {
System.out.println("College and QiluSoftware");
}
public void show(College o) {
System.out.println("College and College");
}
}
class QiluSoftware extends College {
public void show(QiluSoftware o) {
System.out.println("QiluSoftware and MIT");
}
}
class MIT extends QiluSoftware {...}
QiluSoftware shanda = new QiluSoftware();
shanda.show(new College()); //到父类中寻找,打印College and College
shanda.show(new MIT());//本类中无,到父类中找,没有,在本类中找MIT的父类,找到,打印QiluSoftware and MIT
总结:调用顺序为this.show(o)->super.show(o)->this.show((super)o)->super.show((super)o)