java 动态绑定 多态

继承链中对象方法的调用规则:当前类-->父类-->爷类-->..-->祖先类(只能向上找,不能向下找)
优先级:this.method(Obj) > super.method(Obj) > this.method((super)Obj) > super.method((super)Obj)

demo代码:

public class Polymorphic {

public static void main(String[] args) {
Son son=new Son();
Grandson grandson=new Grandson();
Grandson2 grandson2=new Grandson2();

son.method(); //this.method() 当前类Son有method(),就不在使用Father的method()了
grandson.method(); //super.method() 当前类Grandson没有method(),调用的是父类Son的method()
grandson.methods(); //Grandson和Son都没有methods(),向上找到Father的methods()
grandson.method(grandson); //this.method((super)Obj) 当前类以及父类中没有method(Grandson g),则找method(Son s)
grandson2.method(son); //super.method((super)Obj) Grandson2和Son都没有method(Son s),向上找到Father的method(Father f)
/* 结果:
* Son method()
Son method()
Father methods()
G S
F S
*/
Father father_son = new Son(); //声明了一个Father对象,但创建了一个Son对象,father_son是对象的引用,指向创建的Son对象
grandson.method(father_son); //结果:F F 因为参数代表的是声明的对象,并非创建的对象
}

}
class Father {
public void method(){
System.out.println("Father method()");
}
public void methods(){
System.out.println("Father methods()");
}
public void method(Father f){
System.out.println("F F");
}
public void method(Son s){
System.out.println("F S");
}
}
class Son extends Father{
public void method(){
System.out.println("Son method()");
}
}
class Grandson extends Son{
public void method(Son s){
System.out.println("G S");
}
}
class Grandson2 extends Son{
}

猜你喜欢

转载自www.cnblogs.com/jinghun/p/9205103.html