標籤:
多態存在的三個必要條件
一、要有繼承;
二、要有重寫;
三、父類引用指向子類對象。
代碼部分:
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"); }}class C extends B {}class D extends B {}
然後開始搞腦子了:
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(a1.show(a1)); System.out.println(a1.show(a2)); System.out.println(a2.show(a1)); System.out.println(a2.show(a2)); System.out.println(b.show(a1)); System.out.println(b.show(a2)); System.out.println(c.show(a1)); System.out.println(c.show(a2)); System.out.println(d.show(a1)); System.out.println(d.show(a2)); System.out.println("分割線**************************************"); System.out.println(a1.show(b)); System.out.println(a1.show(c)); System.out.println(a1.show(d)); System.out.println(a2.show(b)); System.out.println(a2.show(c)); System.out.println(a2.show(d)); System.out.println(b.show(b)); System.out.println(b.show(c)); System.out.println(b.show(d)); System.out.println(c.show(b)); System.out.println(c.show(c)); System.out.println(c.show(d)); }
運行結果:
A and AA and AB and AB and AB and AB and AB and AB and AB and AB and A分割線**************************************A and AA and AA and DB and AB and AA and DB and BB and BA and DB and BB and BA and D
為了方便理解,我列了下每個類的method table
Ashow(D) -> A.show(D)show(A) -> A.show(A)B,C, Dshow(D) -> A.show(D)show(B) -> B.show(B)show(A) -> B.show(A)
java多態例子