Why use getters and setters in classes? [duplicate]

0

Why do I need to encapsulate the entire class, if I as a programmer know perfectly how to use that variable. I only see need for setters and getters to work on 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;
}
    
asked by anonymous 25.06.2017 / 13:38

1 answer

1

Basically this is one of the concepts of object orientation, encapsulation, in which you can define your variable as 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;
  } 
}

Class main

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 class Person and set within it a private variable of type String named name, in which I want to access it outside of the Person class, for this I created the setter and the getter of the person var, making it possible to access the same in other classes

In the ex that 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 using the method getNome()

    
25.06.2017 / 14:24