Getter and Setter in Java
Problem
A getter reads a private field's value and a setter writes it, following Java's standard getX()/setX() naming convention, so a class's internal fields stay private while still being usable from outside.
Define a Person class with private name and age fields, accessed only through matching getter and setter methods.
Java Program
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class GetterSetterDemo {
public static void main(String[] args) {
Person person = new Person();
person.setName("Maya");
person.setAge(28);
System.out.println(person.getName() + " is " + person.getAge() + " years old");
}
}Output
Core Logic
Pairing every private field with its own getX() and setX() method gives external code a controlled read/write path, following the same naming pattern regardless of which field it's for.
- 1
private String name;andprivate int age;can't be accessed directly from outsidePerson. - 2
setName(String name)andsetAge(int age)assign to those fields — this is the only way external code can change them. - 3
getName()andgetAge()return the current field values — the only way external code can read them. - 4
person.setName("Maya")andperson.setAge(28)populate the object, thengetName()/getAge()read those same values back.
person.getName() returns "Maya" and person.getAge() returns 28, printed together as "Maya is 28 years old".Key Point: This is deliberately just the mechanical get/set pattern, with no validation logic inside the setters — the broader question of why fields are hidden and what a setter should reject belongs to Encapsulation, not to the naming convention itself.