Java ProgramsOOPGetter and Setter

Getter and Setter in Java

beginner·  OOP  ·  Encapsulation

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.

Input
setName("Maya"), setAge(28)
Output
Maya is 28 years old

Java Program

Java
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

Maya is 28 years old

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.

How It Works
  1. 1private String name; and private int age; can't be accessed directly from outside Person.
  2. 2setName(String name) and setAge(int age) assign to those fields — this is the only way external code can change them.
  3. 3getName() and getAge() return the current field values — the only way external code can read them.
  4. 4person.setName("Maya") and person.setAge(28) populate the object, then getName()/getAge() read those same values back.
After both setters run, 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.

Key Concepts

getter methodsetter methodprivate field

Related Programs