Java 向上造型

向上造型  意思为 子类引用的对象转换为父类类型

例如  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

posted @ 2018-11-24 16:57  奋斗的渣渣  阅读(4712)  评论(0编辑  收藏  举报