Java 对象创建的OOP基础知识
以下oo情况:Java 对象创建的OOP基础知识,java,oop,Java,Oop,以下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); Sy
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); }
}
我正在练习面向对象编程。如果我这样启动一个对象会发生什么
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)
“just An A”的实例不是B的实例,这就是强制转换失败的原因
现在您可以这样做:
因为在这种情况下,尽管a
变量的类型只是a
,但其值引用B
的实例。。。所以演员阵容成功了。
您不能将A转换为B,因为A是非B
(B) A // class cast exception
用同样的逻辑,B是一个so
(A) B // true
你试过运行这个吗?输出是不言自明的。如果手头没有编译器/Java安装,您可以使用在线编译器来测试类似的内容。下面是一个例子:
(B) A // class cast exception
(A) B // true