Search code examples
javagetter-setter

Java setter and getter methods


When I am using setter and getter methods, can I use any method name instead of getVariable/setVariable?

In fact can I use

public void abc(String name){
    this.name=name;
}

Instead of

public void setName(String name){
    this.name=name;
}

Solution

  • It is a naming convention that is followed by the programmers to name the getters and setters as getName() and setName(). In normal Java programs even if you don't perform this convention it is not going to cause a problem other than readability(which is of utmost importance). But when you start using frameworks in java, for example the Spring Framework usually searches for getters and setters with the naming conventions getName() and setName() manipulate an object. so it is better to use this naming convention.