向上造型 意思為 子類引用的對象轉換為父類類型
例如 A 是B的父類
A a = new B();
向上造型后 子類 將不再具備其自己定義的方法,只有父類的方法。但若重寫了父類的方法,向上造型的對象的方法為重寫后新的方法。
向下造型:父類引用的對象轉換為子類類型。但是對於父類的引用對象一定要是由子類實例化的,也就是說向下造型的出現一般的情況都是和向上造型一起出現的。
例如:A是父類 B為子類
A a1 = new A();
A a2 = new B();
B b = new B();
B bc = (B)a2;// 不會報錯
B bb = (B)a1;// 報錯
參考例子
public class CaseTest {
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();
B bc = (B)a2;
// B bb = (B)a1;
System.out.println(a1.show(b));
System.out.println(a1.show(c));
System.out.println(a1.show(d));
System.out.println(",,,,,,");
System.out.println(a2.show(b));
System.out.println(a2.show(c));
System.out.println(a2.show(d));
System.out.println(",,,,,,");
System.out.println(b.show(b));
System.out.println(b.show(c));
System.out.println(b.show(d));
}
}
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{
}
運行結果:
A and A
A and A
A and D
,,,,,,
B and A
B and A
A and D
,,,,,,
B and B
B and B
A and D