Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
How does Java solve the class initialization problem Swift was designed to solve?

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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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?

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda