当超类不存在时调用超类的构造函数
Calling constructor of superclass when it doesn't exist
如果我在 java 理论考试中有以下问题,正确答案是什么?
question/task:
创建一个 Circle class 继承自 Shape class 并在其构造函数中调用 Shape class 构造函数。形状 class:
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 部分)恰好涉及如何创建不可实例化的 class:
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
,您将无法扩展它,正是因为 [=20] 中对 super()
的调用=] 无法解决:
private Shape() {}
选项A是正确答案。如果 class 没有定义它,它总是有构造函数,尽管 java 在内部没有为它定义参数构造函数。所以对于默认构造函数调用它不会给出任何错误。
我正在发布 运行 成功并在控制台上打印 hello 的示例。
public class Circle extends Shape {
public Circle() {
super();
System.out.println("Hello");
}
public static void main(String[] args) {
Circle circle = new Circle();
}
}
public class Shape {
private int size;
}
如果我在 java 理论考试中有以下问题,正确答案是什么?
question/task:
创建一个 Circle class 继承自 Shape class 并在其构造函数中调用 Shape class 构造函数。形状 class:
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 部分)恰好涉及如何创建不可实例化的 class:
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
,您将无法扩展它,正是因为 [=20] 中对 super()
的调用=] 无法解决:
private Shape() {}
选项A是正确答案。如果 class 没有定义它,它总是有构造函数,尽管 java 在内部没有为它定义参数构造函数。所以对于默认构造函数调用它不会给出任何错误。
我正在发布 运行 成功并在控制台上打印 hello 的示例。
public class Circle extends Shape {
public Circle() {
super();
System.out.println("Hello");
}
public static void main(String[] args) {
Circle circle = new Circle();
}
}
public class Shape {
private int size;
}