Why use getters and setters in classes? [duplicate]
Why do I need to encapsulate the whole class, if, as a programmer, I know perfectly well how to use that variable. I only see need for setters and getters that work the value of the variable, like this:
void setCommand (string val)
{
string ret = "";
for (char it : val)
ret += toupper(it);
command = ret;
}
But what is the need to use setters or getters like this:
void setMoney (float val)
{
money = val;
}
float getMoney ()
{
return money;
}
1 answers
Basically this is one of the concepts of object orientation, encapsulation, in which you can set your variable to private, and create the getter and setter to be able to access it from another class
Ex:
class Pessoa {
String nome;
public String getNome() {
return this.nome;
}
public void setNome(String s) {
this.nome = s;
}
}
Main class
class main() {
public static void main(String[] args) {
Pessoa pessoa = new Pessoa();
pessoa.setNome("João");
System.out.println(pessoa.getNome());
}
}
In this situation I created the person class and set inside it a private variable of type String called name, in which I want to access it outside the person class, for this I created the setter and the getter of the person var, making it possible to access it in other classes
In the ex I gave, I accessed it from the main class, created an object of type person, and set a name to it "John" from The Method setNome()
of the person class, DPS displayed a name that I passed the same on the screen through the method getNome()