Course contentsShow
← Java
Lesson 345 of 2,8708. Classes and EncapsulationFree lesson

Read-Only Properties: Getters Without Setters

Creating immutable properties by providing only getter methods and initializing fields via constructors.

Read-Only Properties: Getters Without Setters

What you'll learn: How to create object properties that can be read but never changed after construction, making your objects more predictable and safer to use.

The Core Idea

Sometimes you want to expose a piece of information about an object, but you never want that information to change after the object is created. This is called a read-only property or immutable property. You achieve this by providing only a getter method—no setter—and initializing the field through a constructor.

Think of it like a person's birth date: once you're born, that date is set forever. You can ask someone their birth date (getter), but you can't change when they were born (no setter).

How It Works

public class Person {
    private final String birthDate;
    private int age;  // Can change

    public Person(String birthDate, int age) {
        this.birthDate = birthDate;
        this.age = age;
    }

    // Read-only property: getter without setter
    public String getBirthDate() {
        return birthDate;
    }

    // Read-write property: both getter and setter
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Once a Person is created with new Person("1990-05-15", 34), the birth date is permanently locked in. You can call getBirthDate() anytime, but there's no setBirthDate() method, so it can never change.

Notice the final keyword on birthDate—this guarantees the field itself can't be reassigned, even accidentally within the class.

Why Use Read-Only Properties?

  • Safety: Prevents accidental or malicious modification
  • Clarity: Signals to other programmers which values are constant
  • Integrity: Ensures objects maintain valid states throughout their lifetime

Key Takeaway: Read-only properties combine private final fields, constructor initialization, and a getter method without a setter to create values that can be observed but never changed after object creation.