天天看點

java多态的了解案例

public class A {
	public String show(D obj){
		return "A and D";
	}
	public String show(A obj){
		return "A and A";
	}

}

           
public class B extends A{
	public String show(B obj){
		return "B and B";
	}
	public String show(A obj){
		return "B and A";
	}

}


           
public class C extends B{
	

}
           
public 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));
		System.out.println("2:"+a1.show(c));
		System.out.println("3:"+a1.show(d));
		System.out.println("4:"+a2.show(b));
		System.out.println("5:"+a2.show(c));
		System.out.println("6:"+a2.show(d));
		System.out.println("7:"+b.show(b));
		System.out.println("8:"+b.show(c));
		System.out.println("9:"+b.show(d));
		

	}

}


           
結果:
1:A and A
2:A and A
3:A and D
4:B and A
5:B and A
6:A and D
7:B and B
8:B and B
9:A and D

           

a1.show(b);Class A 中沒有show(B obj),B轉向B的父類A,執行A show(A obj)于是return “A and A”

a1.show(c);Class A 中沒有show(C obj),C轉向C的父類B,Class A 中沒有show(B obj),再轉向父類A,執行A show(A obj)于是return “A and A”

a1.show(d);Class A 中有show(D obj),執行A show(D obj)于是return"A and D"

A a2 = new B(); B類是A類的子類,是以語句發生了向上轉型,new B()會在堆記憶體中産生B類的執行個體,A a2會在棧記憶體中産生一個A類的引用。

A a2=new B();會讓a2指向堆記憶體中的new B()的執行個體,但是該執行個體是B類的執行個體,這就會發生向上轉型,如果子類存在與父類相同名和參數的方法,這種情況叫做多态性,子類覆寫父類方法。

a2.show(b);Class A 中沒有show(B obj),B轉向B的父類A,執行A show(A obj),A的show 方法被重寫,執行B show(A obj)于是return “B and A”

a2.show(c);Class A 中沒有show(C obj),C轉向C的父類B,Class A 中沒有show(B obj),B轉向父類A,執行A show(A obj),A的show 方法被重寫,執行B show(A obj)于是return “B and A”

a2.show(d);Class A 中有show(D obj)執行A show(D obj)于是 return “A and D”

b.show(b); Class B 中有show(B obj)于是return “B and B”

b.show(c); Class B 中沒有show(C obj),C轉向C的父類B,執行B show(B obj)于是return “B and B”

b.show(d); Class B 中有繼承了Class A 的show(D obj),執行A show(D obj)于是return “A and D”