+ 2
I need someone to explain to me the point of getters and setters
What I mean is in a class when you define a variable with getters and setters what is the point or rather how does your code benefit from this and when should you use it
2 Answers
+ 4
Basically, when you have a class you'll have private members of the class that you don't want people directly accessing. Setters are methods that you can call from the object in order to change those private variables without directly accessing them. The Getters are methods you can use to indirectly return the value of those variables. This is called encapsulation and it helps you keep those variables hidden away.
Hope that helps out some with understanding what they are.
EXAMPLE:
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
---------------------------------------------
Change value EXAMPLE:
MyClass obj = new MyClass();
obj.setName("Ehsan");