以下oo情况:
class A{
public A(){ System.out.println("Regular constructor of A"); }
public A(int i){ System.out.println("Constructor of A with " + i); }
}
class B extends A{
public B(){
super(3);
System.out.println("Regular constructor of B");
}
public B(int i){ System.out.println("Constructor of B with " + i); }
}
我正在练习oo 编程。如果我以这种方式启动一个对象会发生什么?
B b1 = (B) new A();
但是这样的类型转换对我来说没有意义。输出结果是什么?请说明原因。
最佳答案
当您尝试转换为 B 时,输出将是一个异常,如下所示:
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
at Test.main(Test.java:16)
“只是一个 A”的实例不是 B 的实例,这就是转换失败的原因。
现在您可以这样做:
A a = new B();
B b = (B) a; // No exception!
因为在那种情况下,虽然 a
变量的类型只是 A
,但它的 value 指的是 B 的实例
...所以转换成功。
关于java - 如何创建对象的 OOP 基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977144/