在这种情况下是否需要执行标准构造函数 (Java)?

Is implementation of a standard constructor (Java) necessary in this case?

我有三个这样的class:

public abstract class ClassA extends ClassX {
    protected ClassA() {
        super();
    }
    // more code
}
public class ClassB extends ClassA {
    public ClassB() {
        super();
    }
    // more code
}
public abstract class ClassC extends ClassB {
    public ClassC() {
        super();
    }
    // more code
}

我会说 ClassC 的标准构造函数不是必需的,因为 Java 会在编译期间插入它,因为这个 class 中没有其他构造函数,对吗? 如果为真,我可以将 ClassC 的代码简化为:

public abstract class ClassC extends ClassB {
    // more code
}

现在我会说我不能对 ClassB 做同样的事情,因为构造函数的可访问性从 protected 增加到 public

我问这个问题是因为我对此不是 100% 确定并且认为我可能遗漏了什么。特别是关于将插入到 ClassC 中的标准构造函数,如果我自己不实现的话。在这种情况下,它将具有可访问性 public,因为它继承自 ClassB。对吗?

所以我的问题是:是否可以在不更改代码(尤其是构造函数的可访问性)的情况下删除ClassC中的构造函数,我不能删除ClassB的构造函数是否正确。

Now I'd say that I can't do the same for ClassB since the accessibility of the constructor is increased from protected to public.

这无关紧要,因为它是抽象的 class。构造函数不能直接调用 - 它仅在从 subclass 构造函数链接时使用。

因此,虽然它技术上不同,但如果删除所有构造函数声明,您的代码实际上是相同的。

但是在默认构造函数的可访问性方面,JLS 8.8.9是这里的权威:

If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

  • The default constructor has the same accessibility as the class (§6.6).
  • ...

来自Java specification on 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.

所以你最好不要包含任何这些构造函数。

The rule that the default constructor of a class has the same access modifier as the class itself is simple and intuitive. Note, however, that this does not imply that the constructor is accessible whenever the class is accessible.

  1. 如果不构造构造函数,default empty constructor is automatically created.
  2. 如果任何构造函数未显式调用 super 或 this 构造函数作为其第一条语句,则 call to super() is automatically added.

That means if your constructors are defined with in the scope of the child class then there is no need to call super() explicitly. As in your case you can remove all the constructors. Your program will still compile and run.

希望这对您有所帮助。有关更多信息,请查看共享链接,其中有一些更漂亮的示例。