Why use getters and setters in classes? [duplicate]

this question already has answers here : when to use Setters and Getters? (3 responses) are Getters and Setters mandatory or enablers? (4 responses) Getters and setters are an illusion of encapsulation? (4 responses) Why should I not change the "getter" s and"setter" s? (2 responses) is it really necessary to use methods for mutator and accessor (setter and getter) in PHP? And the performance? (2 responses) Closed for 3 years.

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;
}
Author: Felipe Nascimento, 2017-06-25

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()

 1
Author: Gabriel Victor, 2017-06-25 12:31:04