超类中没有参数的超级函数 Java

Super Function Java with no parameters in superclass

如果我有一个没有属性的 superclass Animal,然后有另一个有一个属性的 subclass Dog,是否可以使用 super() 方法在为 subclass 创建构造函数时?这是示例代码:

public class Animal {
    
    public Animal() { }
}
public class Dog extends Animal {
    
    public int age;
    public Dog(int age){
        super(); // Do I include this?
        this.age = age;
    }
}

我应该或不应该在 Dog class 中调用 super() 函数有什么原因吗?这有什么不同吗?谢谢!

您不需要在此处调用 super(),因为默认情况下从 subclass.

调用无参数超级 class 构造函数

只有在 super class 中有一个带有一些参数的构造函数时,才需要在需要时从 subclass 显式调用它。

From the language spec:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

这意味着,如果您没有显式调用或确实有对 super() 的显式调用,superclass 需要有一个无参数构造函数 - 显式声明一个,或默认构造函数(如果 class 没有其他构造函数,编译器自动添加的无参数构造函数)。

因此,如果代码使用显式 super() 进行编译,这意味着超级 class 确实具有无参数构造函数:因此,如果您省略它,它也会编译并等效地工作super().