Getters, Setters & Validation
Getters, Setters & Validation
In the previous lesson you made fields private using encapsulation. That raises an obvious question: if the fields are private, how does outside code read or change them? The answer is accessor methods (getters) and mutator methods (setters). More importantly, setters give you a single place to enforce rules — so a BankAccount can never have a negative balance, and a Person can never have a blank name.
What Is a Getter?
A getter is a public method that reads and returns a private field. By convention its name starts with get followed by the field name in PascalCase:
Callers write person.getName() instead of person.name. That looks like extra ceremony, but it pays off the moment you need to change how the value is stored or computed — only the getter changes, not every caller.
is. For boolean fields, convention replaces get with is: isActive(), isEmpty(), isVerified(). Many tools (IDEs, frameworks, JSON libraries) rely on this naming convention.
What Is a Setter?
A setter is a public void method that accepts a new value and assigns it to the private field. Its name starts with set:
Right now these setters blindly accept anything. That is not much better than a public field. The real power comes when you add validation.
Adding Validation Inside Setters
Because the setter is the only route into a private field, every piece of code that changes the field automatically goes through your validation. You write the rule once and it is always enforced:
Now any caller that tries person.setAge(-5) gets an IllegalArgumentException immediately — not a mysterious bug somewhere else in the program.
Calling the Setter From the Constructor
You already know that constructors initialise fields. A common mistake is to assign fields directly inside the constructor, bypassing validation. Instead, call your own setters so the same rules apply:
With this design, creating a new Person("", 25) throws immediately — invalid state can never even be constructed.
Read-Only Fields
Sometimes a field should be set once during construction and never changed afterward. Provide a getter but no setter. You can also mark the field final to make the compiler enforce this:
Because accountNumber is final, the compiler refuses to compile any code that tries to reassign it — even inside the class itself.
Putting It All Together
Here is a short program that exercises the BankAccount class above:
Summary
Getters expose private field values without handing over direct control. Setters are the single entry point for changes, which means validation lives in one place and applies every time. Calling setters from constructors ensures an object is valid from the moment it is created. Read-only fields use a getter without a setter, and marking them final gets the compiler to enforce immutability for you.