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 thePerson
class. They cannot be accessed directly from outside the class.public void setName(String name)
: This is the setter method for thename
field. It allows setting the value of thename
field from outside the class.public String getName()
: This is the getter method for thename
field. It returns the value of thename
field.public void setAge(int age)
: This is the setter method for theage
field.public int getAge()
: This is the getter method for theage
field.
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
Person
object. - We use the setter methods
setName()
andsetAge()
to set thename
andage
fields of theperson
object. - We use the getter methods
getName()
andgetAge()
to retrieve the values of thename
andage
fields and print them.