In object-oriented programming, setters and getters are methods used to set and retrieve the values of the private fields (attributes) of a class, respectively. They provide a way to encapsulate the internal state of an object, enabling controlled access to its data.
Here's a simple Java class with private fields, setters, and getters:
public class Person { private String name; private int age; // Setter for name public void setName(String name) { this.name = name; } // Getter for name public String getName() { return name; } // Setter for age public void setAge(int age) { this.age = age; } // Getter for age public int getAge() { return age; } }
Explanation:
private String name;andprivate int age;: These are private fields of thePersonclass. They cannot be accessed directly from outside the class.public void setName(String name): This is the setter method for thenamefield. It allows setting the value of thenamefield from outside the class.public String getName(): This is the getter method for thenamefield. It returns the value of thenamefield.public void setAge(int age): This is the setter method for theagefield.public int getAge(): This is the getter method for theagefield.
Now, let's see how you can use these setters and getters:
public class Main { public static void main(String[] args) { Person person = new Person(); // Using setters to set values person.setName("Alice"); person.setAge(30); // Using getters to retrieve values System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }
In this example:
- We create a new
Personobject. - We use the setter methods
setName()andsetAge()to set thenameandagefields of thepersonobject. - We use the getter methods
getName()andgetAge()to retrieve the values of thenameandagefields and print them.