Although there are already good answers, with good explanations, you had no examples to exemplify the question, so I will post my answer with a simple example to try to add value to the question.
Considering the following structure of class
:
public class ClazzTest {
private long id;
private String nome;
private long atributoImutavel;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public long getAtributoImutavel() {
return atributoImutavel;
}
public ClazzTest(long id, String nome, long atributoImutavel) {
super();
this.id = id;
this.nome = nome;
this.atributoImutavel = atributoImutavel;
}
}
Where the attribute'Imutavel ', does not have setter
and can only be set by the constructor.
Now consider the following class
that uses and handles the class 'ClazzTest':
public class UtilizaClazzTest {
public void manipulaClazzTest(){
ClazzTest clazzTest = new ClazzTest(1 /* id */, "Test" /* nome */, 10 /* atributo imutavel */);
clazzTest.setId(3);
clazzTest.setNome("Fernando");
// mas não consigo setar o atributo imutavel
}
}
So if I only create
getter
public
of an attribute and only allow instanciar (setar) the attribute in the constructor, it will not be changeable by the instance, its value can only be set when it is created .
But this is not an incorrect approach; on the contrary, it is often used for specific purposes, for example if you really want to ensure that the attribute can only be set when the object is created.
Note: In the example, the 'attributeImutavel' attribute could even use the 'operator' (I do not know if this is the definition) final
like this:
private final long atributoImutavel;
So you would be ensuring that the attribute would only be set at instantiation time and could no longer be set by any internal method of class
, thus making it truly 'immutable' after its creation.
But so, as you mentioned @Math in your answer :
Only you have to know / understand why you are doing this.
That's why in college, as you mentioned, you're taught to always create getters
and setters
, because in 99% of business entity cases this is how it will be, then default is private
attribute and getters
and setters
.
I do not know if it looks 'exemplary'.