Java: Getters and setters
Quick summary
- best practice technique for allowing users to set field values
- set method has user pass an argument;
thiskeyword sets the argument as the value - get method retrieves the value of the argument set by the set method
- this technique helps protect code from users setting invalid values
Eclipse example: getter_and_setter_methods
When you create an instance variable in a class, highlight the variable, right-click, and select Source > Generate Getter and Setter methods. This will insert something like the following:
public class Keyboard {
private String functionKeys;
public String getFunctionKeys() {
return functionKeys;
}
public void setFunctionKeys(String functionKeys) {
this.functionKeys = functionKeys;
}
}
Sponsored
This allows you to easily change the String functionKeys as you need it. You’ve encapsulated it from users changing it, screwing it up, etc.
Now the user can set the value of functionKeys through the setter method, and then get that value. Here’s an example:
public class App {
public static void main(String[] args) {
Keyboard myKeyboard = new Keyboard();
myKeyboard.setFunctionKeys("f11, f10, f9");
myKeyboard.getFunctionKeys();
}
}
Here I’ve instantiated the class with an object called myKeyboard. I then set the value by passing an argument to setFunctionKeys method. The class then sets functionKeys as that value. I then get the value by using the getter method: getFunctionKeys(). Using this technique, I have encapsulated the variable against change by the user. If I wanted, I could entirely modify the meaning of the functionKeys string and users wouldn’t have to change anything about my code.
It’s pretty common with APIs to provide getter and setter methods to users. You don’t want to expose the inner workings of your classes. You just want to provide users with controls in order to use it.
About Tom Johnson
I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, agent skills, tech comm careers, and more. Check out my AI courses for more on the latest in AI and tech comm. If you're looking for info about documenting APIs, see my API documentation course.
If you're a technical writer and want to keep on top of the latest trends in tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me.
Finally, I want to note a couple of things. I usually write the first drafts of my posts myself and then use AI to improve accuracy, clarity, and detail in places, so my writing is a mix of human and AI. (Hopefully that's not too off-putting.) Also, the opinions I express on my blog are my own perspectives, not those of my employer.