java - 当父类(super class)不存在时调用父类(super class)的构造函数

标签 java class subclass superclass

如果我有以下关于 java 理论测试的问题,正确答案是什么?

问题/任务:

创建一个继承自Shape类的Circle类,并在其构造函数中调用Shape类的构造函数。形状类:

public class Shape {
    private int size;
}

选择正确答案:

答:

class Circle extends Shape{

    Circle(){
        super();
    }
}

乙:

"You can't call constructor of Shape class as it doesn't exist"

有人说正确答案是B,但我不明白为什么不能是A? Java 不会创建默认构造函数并调用它吗?

最佳答案

根据官方 Java 语言规范 (JLS),section 8.8.9 :

If a class contains no constructor declarations, then a default constructor is implicitly declared.

通读该部分表明,当 Shape 被编译时,它获得了一个构造函数,就像由

定义的一样
public Shape() {}

它是 public 因为 Shape 是 public 并且隐式调用 super(); 因为它是空的。

很明显你是正确的,选项 A 是答案。

但是选项 B 呢?碰巧的是,JLS 的下一部分(8.8.10 部分)恰好处理了如何创建一个不可实例化的类:

A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of a default constructor, and by declaring all constructors to be private (§6.6.1).

在实践中,如果您手动声明一个 private 空构造函数到 Shape,您将无法扩展它,正是因为调用了 super( )Circle 中无法解析:

private Shape() {}

关于java - 当父类(super class)不存在时调用父类(super class)的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992735/

相关文章:

python - 如何在python中使用print显示类实例

python - 子类化 numpy ndarray 问题

Java - 连接到亚马逊

java - JPA/Hibernate 返回 BigDecimal 不长

java - log4j - 指向多个 log4j.properties 文件之一

java - 如何防止 CXF 日志记录?

c++ - 这是什么错误: "no appropriate default constructor available"?

c++ - 是否可以从 C++ 中此类中定义的结构内部调用类方法?

ios - 将 CCSprite 的子类添加到场景中

c++ - auto之前的私有(private)类的实例