第1个回答 2021-05-27
package Test2;
public class A extends B{
public static void main(String[] args) {
B b=new A();
//此为向下转型,当父类转型成子类时(不需要强制转型),编译和运行都不会报错
b.setS("this b");
System.out.println(b.getS());
A a=(A)new B();
//此为强制转型,当子类被强制转型成父类时,编译不会报错,但是运行会报错
a.setS("this a");
System.out.println(a.getS());
}
}
class B{
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
下面是输出结果
this b
Exception in thread "main" java.lang.ClassCastException: Test2.B cannot be cast to Test2.A
at Test2.A.main(A.java:8)