Getter
- Java course
- Intermediate
- Lesson 25/116
- 5 min
Learn accessor methods with getX.
Getter method
To read the value of a private field, you write a getter method. A getter returns the field's type and is usually named with a get prefix: getName, getBalance.
Example: class Player { private String name; public String getName() { return name; } }. Here the getName method returns the value of the name field. From outside, p.name cannot be written, but p.getName() can be called. A getter keeps how the field is read under control; if the reading logic changes later, only the getter is updated. This keeps the class's internal design flexible.
Getter naming
Getter methods are usually written with a get prefix and the field name's first letter capitalized. For name the getter is getName, for balance it is getBalance.
For boolean fields an is prefix is also used: for active the getter is isActive. This naming is a common convention in Java; it improves code readability. Many libraries rely on this convention. When writing getters, it is important to capitalize the field name correctly; name becomes getName, not getname.
Practice Add a getter to Player
Define a class Player. Add a private String name field. Write a public String getName() getter returning name. Add a void setName(String n) method; its body assigns name = n;. In main create a Player instance, call setName("Alex") and print the result of getName().
Starter code
// Define the Player class
// Add a private name field and getter
// Add setName method and mainSample solution
class Player {
private String name;
public String getName() {
return name;
}
void setName(String n) {
name = n;
}
public static void main(String[] args) {
Player p = new Player();
p.setName("Alex");
System.out.println(p.getName());
}
}Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the getter parts
| Term | Meaning |
|---|---|
public |
Access modifier |
String |
Return type |
getName |
Method name |
return name |
Body |
2 How is the getter for the age field named?
- getage
- ageGet
- readAge
- getAge Correct answer
Explanation: GetAge — get prefix and field name with first letter capitalized.
3 Complete the getter body
public String getName() {
____;
}
public String getName() {
return name;
}
Explanation: The getter returns the field's value.