Java Getter and Setter
Getter and setter methods are public methods used to access and modify the private variables of a class.
Getter Method:
A getter method’s name starts with “get” followed by the field name and it does not have any parameters.
For example, if there is a private field name, create a getter method getName() to get the value of name:
1 | public class Person { |
Setter Method:
A setter method’s name starts with “set” followed by the field name, and it has a parameter to pass the new value to be set.
For example, to set the value of the name field, create a setter method setName():
1 | public class Person { |
Usage
By using getter and setter methods, you can access and modify private fields from outside the class while adding validation logic and control to ensure data consistency and security.
1 | public class Main { |
In the example above, the Person class has a private field name, and public getter and setter methods getName() and setName(). The Main class demonstrates how to use these methods to set and get the value of the name field, ensuring encapsulation and providing a way to control the access and modification of the private field.