2
In object-oriented programming in Java, when I create any attribute or private field, without their respective methods getter
and setter
has to define the attribute as final
or need not?
For example:
public class Pessoa {
private String nome;
private String endereco;
private int idade;
private double salario;
public Pessoa(String nome, String endereco, int idade, double salario) {
this.nome = nome;
this.endereco = endereco;
this.idade = idade;
this.salario = salario;
}
}
In this class above as you see, it lacks the methods getter
and setter
of the respective attributes or fields, in which case it would be necessary to define them as final
?
It is not required. The keyword
final
is used to define a value that cannot be changed ( and therefore must be initialized together with the object ). If you want to have a private attribute and yet it is variable in its value. there is no need to declare it asfinal
– Israel Merljak