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

207
Visualizações
How to declare a method that cannot change the class members in Java?

In C++ we do a constant method, and so it can't change the value of the class members, but how can I do it in Java? I tried the final method declaration, which would be the equivalent to the consts in C++, but final methods are another different thing. I want to make a getter method, so it cannot change the values, only read it. Like a read-only method.

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

0

In Java, it's not possible to declaratively prevent a method from changing non-final fields. There's no such thing as "const correctness" in Java.

If a class field is non-final, then it can be changed by any method of the class.

Note that final works differently on fields and variables versus methods and classes:

  • A final field or variable is a constant. Its value cannot be changed once assigned.
  • A final method cannot be overridden by child classes. final on methods has nothing to do with "constness".
  • A final class cannot be extended. final on classes has nothing to do with "constness".

Your options in Java are:

  1. Make your class immutable (i.e. mark all its fields final).
  2. Just write your getters (and other non-mutator methods) carefully :)

One more note. Even on fields and variables, Java's final differs from C++'s const. For example:

  • final variables can't be changed once assigned, but you can assign them after the declaration. Example:

      final int value;
      if (condition) {
          value = 1; // Ok!
      } else {
          value = 2; // Ok!
      }
      value = 3; // Compile error: value already assigned.
    
  • final class fields must be assigned - either directly or from within a constructor. But these fields may be assigned anywhere within a constructor. There's no special thing like C++'s "initializer list" in Java.

  • The field/variable/parameter declaration final Object obj in Java is roughly equivalent to a (const-)reference to a non-const object in C++. This means, you can't re-assign the reference, but you can change the referenced object itself. An example:

      // Note that (obsolete) Date class is mutable in Java.
      final Date myDate = new Date();
    
      myDate = new Date(); // Compilation error: can't reassign a final reference!
    
      myDate.setTime(4711); // Ok, mutating referenced object is allowed!
    
over 4 years ago · Santiago Trujillo Relatório

0

You can not do that. Final method means it can't be overriden.

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