- 哪些函數(shù)能夠調(diào)用宰睡,取決于reference的類型
- 對于被override 的函數(shù),調(diào)用哪個版本觅闽,取決于object的類型
- 如果非要調(diào)用reference 沒有的類型袜漩,可以強制類型轉(zhuǎn)換成object的類型
class A{
public String show(D obj){
return "A and D";
}
public String show(A obj){
return "A and A";
}
}
class B extends A{
public String show(B obj){
return "B and B";
}
public String show(A obj){
return "B and A";
}
// 繼承的一個隱形的函數(shù)
//public String show(D obj){
// return "A and D";
//}
}
class C extends B{}
class D extends B{}
public class Test{
public static void main(String[] args){
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("1-"+a1.show(b));
// "A and A", 因為reference A可以自動匹配b
System.out.println("2-"+a1.show(c));
// "A and A", 同理
System.out.println("3-"+a1.show(d));
// "A and D", 就近匹配
System.out.println("4-"+a2.show(b));
// "B and A", 因為reference是A,匹配的是public String show(A obj)度液, 但是這個在B里被重寫厕宗,所以是"B and A"
System.out.println("5-"+a2.show(c));
// "B and A", 同理
System.out.println("6-"+a2.show(d));
// "A and D"
System.out.println("7-"+b.show(b));
// "B and B"
System.out.println("8-"+b.show(c));
// "B and B"
System.out.println("9-"+b.show(d));
// "A and D", B里面有三個函數(shù)的
}
}