3

From a quote I read 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.

So it seems like there is some programming paradigm behind this statement? Since I'm using Java and there is no such restriction in Java, I want to know how Java solves this problem.

Boann
  • 48,794
  • 16
  • 117
  • 146
NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64
  • 3
    As far as I know, Java doesn't solve this issue, you just have to be very careful not to mess up :) – Sweeper Nov 23 '20 at 06:32
  • Most Java IDEs will pop up a warning if you try to call a non-final method in the constructor, saying something along the lines of "Warning: Overridable method call in constructor." So yes, you have to be careful, but modern IDEs are here to help you. – Charlie Armstrong Nov 23 '20 at 07:00

1 Answers1

3

In Java, the super constructor is run before the subclass constructor - the complete opposite of what happens in Swift. And There is nothing preventing you from calling an overridden method in the superclass constructor, but that doesn't mean you should do it. See this related question:

Why methods called on class constructor should be final?

Basically, when you call an overridden method, there is a potential that you are accessing un-initialised fields, or just doesn't do what the superclass expects in general.

There are legitimate usages of this though:

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

In Swift, the superclass initialiser can call overridden methods without problems (as long as all the stored properties are initialised), because by that time, the properties of the whole class hierarchy is fully initialised.

There are tools like SonarQube that picks up problems like these, but otherwise the Java compiler doesn't do it. If you ask why, well, it's that whole "control vs safety" tradeoff - do you want more fine-grained control over your code, or more safety?

Sweeper
  • 213,210
  • 22
  • 193
  • 313