Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对象创建的OOP基础知识_Java_Oop - Fatal编程技术网

Java 对象创建的OOP基础知识

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

以下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); }
    }
我正在练习面向对象编程。如果我这样启动一个对象会发生什么

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