Although there are already good answers, with good explanations, had no examples to exemplify the question, so I’ll 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 'assignable', does not have setter
and can only be set by the constructor.
Now consider the following class
using and handling 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 the getter
public
of an attribute and only allow instantiation(setar) the attribute in the constructor, it will not be changeable by the instance, its value can only be set at the time it is created.
But, this is not an incorrect approach, on the contrary, it is widely used for specific purposes, for example if you really want to ensure that the attribute can only be set at the time of the creation of the object.
Note: In the example, the attribute 'attributable' could even use the 'operator' (I don’t know if this is the definition) final
thus:
private final long atributoImutavel;
Thus you would be ensuring that the attribute would only be set at the time of instantiation and could no longer be set by any internal method of class
, making it truly 'imutavel' after its creation.
But so, as you quoted @Math in your answer:
"You can perfectly not provide any public Setter method for an attribute if you so desire"
You just have to know/understand why you’re doing this.
That’s why in college like you said, you’re taught to always create the getters
and setters
, because in 99% of cases of business entities this is how it will be, so by default it is attribute private
and getters
and setters
.
I don’t know if it was 'exemplifiable''.
Yes. It was very 'exemplifiable' and of course. Thank you!
– emanuelsn