java - 当父类(super class)没有构造函数时,如何在子类中声明构造函数

标签 java inheritance constructor

我正在尝试为子类实现构造函数,但是在编译时我不断收到“错误:需要类、接口(interface)或枚举”

我的整体代码如下所示:

public class Super{
    //methods go here, no constructor.
}

这是我尝试过的方法,但没有成功:

public class Sub extends Super{
    private boolean myCondition;
    public Sub(boolean condition){
        super();
        myCondition = condition;
    }
}

我假设我不需要在 subs 构造函数中调用 super(),因为编译器应该隐式调用它。

谢谢。

最佳答案

每个类都有一个构造函数。如果您不指定,您将获得一个默认构造函数。 JLS-8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

所以Super(一个public类)有一个由编译器插入的默认构造函数,看起来像

public Super() {
  super();
}

关于java - 当父类(super class)没有构造函数时,如何在子类中声明构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024102/

相关文章:

c# - 有没有办法在 C# 中获取 F# 的构造函数参数是自动不可变私有(private)成员功能?

java - "cannot find symbol"尽管变量名称正确

c++ - 为什么我必须通过this指针访问模板基类成员?

java - 在 Java 中创建克隆函数而不抛出 CloneNotSupportedException 异常

c# - 更改基类属性 setter 行为

c++ - 派生类中的成员新/删除重载有用吗?

java - 关于继承和构造函数中 Java 8 编译器增强的说明

javascript - 使用 JavaScript 函数添加动态 HTML 内容

java - 在 Java 中从 DataSource 获取 Connection 对象

java - 不同屏幕尺寸的android布局问题