java多型經典例子
阿新 • • 發佈:2018-12-23
直接上程式碼
package com.carrot.core;
/**
* Desc:
* Date: 2017-09-20 16:52
* Author:GooDn19H7
*/
class A {
public String show(D object) {
return "A and D";
}
public String show(A object) {
return "A and A";
}
}
class B extends A {
public String show(B oject) {
return "B and B";
}
public String show(A object) {
return "B and A";
}
}
class C extends B {
}
class D extends B {
}
public class Polymorphism {
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));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("--------------------------------------------");
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("--------------------------------------------");
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));
}
}
分析
多型機制遵循的原則概括為:當超類物件引用變數引用子類物件時,被引用物件的型別而不是引用變數的型別決定了呼叫誰的成員方法,但是這個被呼叫的方法必須是在超類中定義過的,也就是說被子類覆蓋的方法,但是它仍然要根據繼承鏈中方法呼叫的優先順序來確認方法,該優先順序為:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)
從上面的程式中我們可以看出A、B、C、D存在如下關係。
首先我們分析5,a2.show(c),a2是A型別的引用變數,show(c)在A類中找發現沒有找到,於是到A的超類中找(super),由於A沒有超類(Object除外),所以跳到第三級,也就是this.show((super)O),C的超類有B、A,所以(super)O為B、A,this同樣是A,這裡在A中找到了show(A obj),同時由於a2是B類的一個引用且B類重寫了show(A obj),因此最終會呼叫子類B類的show(A obj)方法,結果也就是B and A。按照同樣的方法我也可以確認其他的答案。
引用