Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 201 ยท Object-Oriented Programming

Encapsulation, Getters and Setters

Learn encapsulation in Java - private fields, getters and setters done right, protecting invariants, hiding the representation and making defensive copies.

Encapsulation means an object keeps its data to itself and lets the outside world work with it only through methods it chooses. The fields are private; the methods are the doors. Because every change goes through a door, the object can check each request and refuse the ones that would leave it in a nonsense state, such as a negative stock count or an end date before its start date.

You learned the mechanics in Access Modifiers. This lesson is about using them well: protecting an object's rules (its invariants), writing getters and setters that add value instead of ceremony, hiding how data is stored so you can change it later, and the defensive copies that stop mutable objects from leaking out through the back door.

The problem with public fields

Here's a class that exposes its fields directly. Nothing stops other code from writing whatever it likes:

Java Public fields let anyone break the rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The booking ends up with minus four guests and a total of zero, and nothing complained. In a real program the bad value would be stored, emailed or billed long before anyone noticed, and finding which of hundreds of lines did guests = -4 would take a debugger and patience.

Protecting invariants

An invariant is a rule that must be true for every object of a class at all times (outside the middle of a method call). For a booking: at least one guest, at least one night. Encapsulation enforces it in two places:

  1. The constructor refuses to create an invalid object.
  2. Every method that changes state refuses to break the rule.

If both hold, every Booking that exists is valid, and no other code ever needs to check again.

Java Private state that validates every change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few design choices are worth noticing:

  • There's no setNights method. Instead there's extendBy, an operation that means something in the problem domain. Methods named after what users do ("extend", "add guest", "cancel") are easier to validate and to read than raw setters.
  • Bad arguments throw IllegalArgumentException; a valid request at the wrong moment (the booking is full) throws IllegalStateException. Those are the standard exceptions for these two cases (Throwing Exceptions).
  • The check happens before the change. If extendBy changed nights first and then validated, a failed call would leave the object broken.

Getters and setters

A getter returns a field's value; a setter changes it. Java's naming conventions come from the JavaBeans specification, and frameworks, IDEs and serialization libraries all rely on them:

Field Getter Setter
String name getName() setName(String name)
int age getAge() setAge(int age)
boolean active isActive() setActive(boolean active)

A setter earns its place when it validates or normalizes its input. Here the setter trims spaces and rejects blank names, and the getter for a boolean uses the is prefix:

Java Setters that validate and normalize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The constructor calls setName, so the rule lives in one place. That's fine here because Customer isn't designed for subclassing; calling overridable methods from a constructor of a class that is extended can cause trouble, which you'll see in The super Keyword.

Not every field needs a setter (or a getter)

IDEs can generate a getter and setter for every field with one click, and that's a trap. A class with private fields and a public setter for each of them is barely better than public fields: any code can still set any value at any time. Ask for each field:

  • Should it change after construction? If not, make it final and give it no setter. An ID, a creation date or a price agreed at booking time shouldn't change.
  • Does it change only in specific ways? Then offer operations (deposit, extendBy, cancel) instead of a setter.
  • Do callers need to read it at all? Internal bookkeeping fields need neither getter nor setter.

The guideline often quoted is "tell, don't ask": instead of asking an object for its data, deciding something and setting the result back, tell the object what you want and let it decide. account.withdraw(50) beats account.setBalance(account.getBalance() - 50), because only the first can enforce "no overdraft".

Hiding the representation

Because callers only see methods, you can store data however you like and change your mind later. This Workout class stores a single number of seconds but lets callers think in minutes and hours:

Java Changing the inside without changing the outside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

getMinutes looks like a getter, but no minutes field exists; it's computed. If you later decide to store milliseconds, or a java.time.Duration, only the inside of Workout changes. No caller notices. That freedom is the long-term payoff of encapsulation, and the reason to prefer methods even when a public field would "work".

Defensive copies

private protects a field, but not necessarily the object the field points to. If a field refers to a mutable object, such as an array, a List or a StringBuilder, then any outside code holding a reference to that same object can change your state behind your back. There are two leaks:

  1. Coming in: the constructor stores the caller's list, and the caller keeps modifying it.
  2. Going out: a getter returns your internal list, and the caller modifies it.
Java Leaky references and the defensive-copy fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The leaky playlist ends up empty even though the class has no method for removing songs. The safe one prints [Intro, Rain, Encore]: the caller's later change and the attempted add on the returned list never reached it. It makes a private copy in the constructor and returns a read-only copy from the getter, so the only way to add a song is add, which validates. Note that final on the field didn't help the leaky class: final stops the field from pointing somewhere else, not the list from changing (Constants and final).

Your options when returning a collection:

  • List.copyOf(list): an unmodifiable snapshot. Later changes inside the object don't show up in it. It rejects null elements.
  • Collections.unmodifiableList(list): a read-only view. It's cheaper (no copying), and callers see later changes made through the object.
  • new ArrayList<>(list): a mutable copy the caller can do anything with, without affecting you.

The same applies to arrays (return array.clone()) and to any other mutable type, such as the legacy java.util.Date. Immutable types like String, Integer, LocalDate and records of immutable values need no copies at all, which is one of many reasons to prefer them. That's the topic of the next lesson.

Copy before validating when you take a mutable argument. If you validate the caller's list and then copy it, another thread could change it between the two steps. Copy first, then check your own copy.

Encapsulation in modern Java

  • Records (record Point(int x, int y) {}) generate private final fields, a constructor and accessor methods named x() and y(), with no setters. A compact constructor can validate. They're encapsulation for data carriers with almost no code (Records).
  • Packages and modules encapsulate at a larger scale: package-private classes hide helpers, and modules hide whole packages.
  • Getter naming: records and many modern APIs use name() rather than getName(). Both are fine; be consistent within a project, and use get/is when a framework expects JavaBeans names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of making a field private and changing it only through methods?

    Because every change passes through code the class controls, it can reject invalid values. Reading can still be allowed through getters.
  2. 2. A class has private final List<String> tags; and List<String> getTags() { return tags; }. What can a caller do?

    The getter returns a reference to the internal list. final only stops the field from being reassigned, and private only hides the field's name; the list itself is still mutable. Return List.copyOf(tags) instead.
  3. 3. Which method best follows "tell, don't ask" for a bank account?

    withdraw tells the account what you want and lets it enforce its rules, such as no overdraft. The other versions put the logic outside the class.
  4. 4. A setter does this.count = value; if (value < 0) throw new IllegalArgumentException();. What's wrong?

    Always check first and change second. Here the exception is thrown after the bad value was already stored.
  5. 5. What does a getter like int getMinutes() { return totalSeconds / 60; } show?

    There is no minutes field. Because callers only see the method, the class can store time however it wants and change that later without breaking anyone.

Summary

  • Encapsulation keeps fields private and exposes behavior through methods, so objects can enforce their invariants.
  • Validate in the constructor and in every state-changing method, and check before changing.
  • Prefer meaningful operations (extendBy, withdraw) over raw setters; give fields no setter when they shouldn't change.
  • Getter and setter names follow JavaBeans conventions: getX, isX for booleans, setX.
  • Methods hide the representation, so you can change how data is stored without breaking callers.
  • Mutable fields need defensive copies coming in and going out (new ArrayList<>(...), List.copyOf, clone()); final alone doesn't protect them.

Next: Immutable Classes, where you'll build objects that can't change at all, and see why that makes so many problems disappear.