Java 是如何解决 class 初始化问题 Swift 被设计来解决的?

How does Java solve the class initialization problem Swift was designed to solve?

摘自我读到的一句话 online:

One of Swift’s rules is that you must initialise all the properties of a class before initialising the superclass. This avoids issues that can arise if a super initialiser calls a method which is overridden resulting in inconsistent state.

所以这句话背后似乎有某种编程范式?因为我用的是Java,而Java里面没有这个限制,想知道Java是怎么解决这个问题的

在 Java 中,超级构造函数 运行 在子 class 构造函数之前 - 与 Swift 中发生的情况完全相反。并且没有什么可以阻止您在 superclass 构造函数中调用重写的方法,但这并不意味着您应该这样做。请参阅此相关问题:

Why methods called on class constructor should be final?

基本上,当您调用重写的方法时,您可能会访问未初始化的字段,或者只是不执行 superclass 通常所期望的。

虽然有合法的用法:

In Java, is there a legitimate reason to call a non-final method from a class constructor?

在Swift中,superclass初始化器可以毫无问题地调用重写的方法(只要所有存储的属性都被初始化),因为到那时,整个class 层次结构已完全初始化。

有像 SonarQube 这样的工具可以解决这些问题,但 Java 编译器不会这样做。如果你问为什么,嗯,这就是整个“控制与安全”的权衡——你想要对你的代码进行更细粒度的控制,还是更安全?