Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 4

Getters, setters and validation

The controlled doors in and out of an object

20m55 XP
→→→

What you'll be able to do

  • Write getters and setters with the conventional Java names
  • Choose between read-only, write-only and read-write access
  • Implement four different validation strategies and say when each fits
  • Explain why a setter without validation is a design smell
1

Getters & Setters

Accessors: get, is, set

Java has no built-in properties, so the community agreed on three prefixes. Follow them and every tool and teammate understands your class.

The naming convention (memorise it — tools depend on it)

getX()
Returns the value of field x. Same type as the field, no parameters.
isX()
The getter for a boolean field: isActive(), not getActive().
setX(value)
Changes field x. Takes one parameter, usually returns void — and should validate.

Not every field needs both doors

Access you exposeWhat you writeTypical example
read-writegetter + validating settera student's age
read-onlygetter onlyan account balance (changed only by deposit/withdraw)
write-onlysetter onlya password hash you never hand back
noneneitheran internal cache or counter nobody outside needs

Start with 'none' and add a door only when a real caller needs it. Generating getters and setters for every field by reflex is how encapsulation quietly disappears.

A class with three accessors

Notice there is no `setName`: the name is read-only. Try adding a validating `setName` that refuses an empty string.

Output
Press Run to execute this example.

Prefer behaviour over setters

account.setBalance(newValue) tells the reader nothing. account.deposit(100) and account.withdraw(50) describe *intent*, keep the rules inside, and make the audit trail obvious. Setters are for plain data; behaviour is for anything with rules.

Prove it — coding challenges

2

Validation

Four ways to refuse bad data

'Reject it' is not one decision — it is four, and the right one depends on who is calling.

Validation strategies, weakest to strongest

  1. Ignore silently — if (amount <= 0) return;. Simple, but the caller never learns anything went wrong. Fine for demos, risky in real systems.
  2. Clamp to a legal range — a volume above 10 becomes 10. Great for settings, wrong for money.
  3. Return a boolean — boolean withdraw(double amount) returns false on refusal, so the caller can react. This is the style used in this course's challenges.
  4. Throw an exception — throw new IllegalArgumentException("amount must be positive"). The real-world default for programming errors, because it cannot be ignored by accident.
Validate in the constructor too — by reusing the setter
Main.java
1public Product(String name, double price) {
2 this.name = name;
3 setPrice(price); // one rule, used by constructor and callers alike
4}
An object must be valid from birth, not just after the first setter call. Calling the validating setter from the constructor keeps the rule in one place.
Boolean-returning validation

Predict all four lines. Then make the constructor pass `-1` and check that the object still starts at a legal price.

Output
Press Run to execute this example.

A refused change must change nothing

Check first, assign second. If you write balance = balance - amount; and *then* test for a negative balance, the object spends a moment in an illegal state — and any exception in between leaves it corrupted. The hidden tests in the challenges check exactly this.

Prove it — coding challenges

Common mistakes

Wrongpublic boolean getActive() { return active; }
WhyBoolean getters conventionally use the `is` prefix; tools and teammates expect `isActive()`.
Fixpublic boolean isActive() { return active; }
Wrongpublic void setAge(int age) { age = age; }
WhyShadowing again — the field never changes.
Fixthis.age = age; after validating.
WrongGenerating a getter and setter for every single field automatically.
WhyThat re-exposes all state and defeats the purpose of `private`.
FixExpose only what callers need, and prefer intent-revealing behaviour.

Lesson playground

Free practice

A thermostat with a clamped range. Add an `isSafe()` method that returns true when the temperature is between 16 and 26.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

This setter clamps instead of rejecting. What is printed?

Main.java
1class Volume {
2 private int level;
3
4 public void setLevel(int level) {
5 if (level < 0) {
6 this.level = 0;
7 } else if (level > 10) {
8 this.level = 10;
9 } else {
10 this.level = level;
11 }
12 }
13
14 public int getLevel() {
15 return level;
16 }
17}
18
19public class Main {
20 public static void main(String[] args) {
21 Volume v = new Volume();
22
23 v.setLevel(15);
24 System.out.println(v.getLevel());
25
26 v.setLevel(-3);
27 System.out.println(v.getLevel());
28
29 v.setLevel(7);
30 System.out.println(v.getLevel());
31 }
32}

Summary

  • `getX()`, `isX()` for booleans, `setX(v)` — the convention every Java tool assumes.
  • Expose the minimum: read-only, write-only or nothing is often the right answer.
  • Validate by ignoring, clamping, returning a boolean, or throwing — pick deliberately.
  • Always check before you mutate, and reuse the setter's rule inside the constructor.