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