Skip to content

Private State & Methods

The Course
•
20 min study

A private field cannot be accessed directly from another top-level class. Public methods can expose useful operations without exposing every internal assignment. This is encapsulation: the object owns rules about its state. A getter reads a field; a setter assigns one. You do not need either automatically for every field. The public operations form the class's API: what other code can call and the behavior it can rely on.

A session's planned duration can stay fixed while completion changes. Instead of allowing any caller to write done, expose complete(). Calling it twice should still mean completed, not toggle the state back or add time twice. This operation is idempotent: repeating it has the same final effect as doing it once.

Choose what callers should be able to do

Return information through methods such as remaining(), and update state through methods named after an action. A method returning false can report that a proposed change was rejected. On Day 6, exceptions will offer another way to signal invalid input. Both approaches need a clear rule about whether state changed.

The keyword public allows the model's methods to be called by other classes. For now, keep all classes in the supplied workspace and use public for the operations intended for callers, and private for the data they should not assign directly. Other access rules can wait until you need to organize a larger project.

Complete once, read many times Java
public class Main {
    public static void main(String[] args) {
        Session session = new Session(25);
        System.out.println(session.remaining());

        session.complete();
        session.complete();

        System.out.println(session.remaining());
    }
}

class Session {
    private final int minutes;
    private boolean done;

    Session(int minutes) {
        this.minutes = minutes;
    }

    public void complete() {
        done = true;
    }

    public int remaining() {
        if (done) {
            return 0;
        }

        return minutes;
    }
}
Check your prediction
Text
25
0

The completion operation assigns a fact; it does not flip the boolean. The second call leaves the same state as the first. A caller can ask for remaining time without learning how the boolean is stored.

Reject an update without changing state Java
public class Main {
    public static void main(String[] args) {
        Budget budget = new Budget();
        System.out.println(budget.add(-5));
        System.out.println(budget.add(10));
        System.out.println(budget.total());
    }
}

class Budget {
    private int minutes;

    public boolean add(int amount) {
        if (amount < 0) {
            return false;
        }

        minutes += amount;
        return true;
    }

    public int total() {
        return minutes;
    }
}
Check your prediction
Text
false
true
10

Validation occurs before mutation. If you added the amount before testing it, the false result would conceal a changed budget. The contract includes both the returned boolean and the state afterward.

Compiler error: private access Java
public class Main {
    public static void main(String[] args) {
        Secret secret = new Secret();
        System.out.println(secret.value);
    }
}

class Secret {
    private int value = 25;
}
Read the diagnostic

Main cannot read a private field declared by the separate top-level Secret class. Expose an intentional method if callers need this information. Do not remove private merely to silence the error without deciding the API.

An operation protects a rule, not just a field

Private fields prevent callers from assigning them directly. The public methods decide which changes are meaningful. A getter plus an unrestricted setter for every field can expose almost the same invalid changes as a public field; ask what behavior the object should actually offer.

For a completion flag, complete() says what the change means and can be safe to repeat. A caller should not need to read the flag, invert it and write it back merely to mark completion: that sequence would undo completion on a repeated request. A toggle and an idempotent complete operation have different contracts.

Start with a session that is not done and send the same "mark it done" request twice:

Aftertoggle done = !donecomplete() sets done = true
first requestdonedone
repeated requestnot donedone

Only the second design keeps its promise when a request arrives twice.

Debug a plausible mistake

The helper method receives a fresh call each time, but the object survives those calls. Resetting its field inside increment confuses local calculation with persistent object state. Inspect which object receives each call.

Exercise

Repair persistent object state

Increment first twice and keep second independent. The outputs must be 2 and 0. Make the repair in Counter; do not replace the printed values with literals. Predict what the current program actually prints before changing it. Make the smallest repair, then add a third first.increment() and check that it reports 3. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
public class Main {
    public static void main(String[] args) {
        Counter first = new Counter();
        Counter second = new Counter();
        first.increment();
        first.increment();
        System.out.println(first.current());
        System.out.println(second.current());
    }
}

class Counter {
    private int count;

    public void increment() {
        count = 0;
        count++;
    }

    public int current() {
        return count;
    }
}
Hint 1: the idea

Only construction should establish this counter's initial zero value.

Hint 2: a first step

Remove the unintended reinitialization from the changing operation.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        Counter first = new Counter();
        Counter second = new Counter();
        first.increment();
        first.increment();
        System.out.println(first.current());
        System.out.println(second.current());
    }
}

class Counter {
    private int count;

    public void increment() {
        count++;
    }

    public int current() {
        return count;
    }
}

Expected output after repair:

Text
2
0

The bug was count = 0; inside increment: every call wiped the earlier count, so first always reported 1. The field already starts at 0 when the object is constructed, so the reset line can simply go. A third call reports 3 only after the fix; with the bug it would still report 1.

Your turn

Exercise

Protect a class pass

A gym pass allows a fixed number of visits. Implement Pass with:

  • a private int field for the visits left, set by the constructor Pass(int visits);
  • public boolean use(), which uses one visit and returns true, or returns false and changes nothing when no visits are left;
  • public int left(), which returns the visits left.

In main, create a pass with 2 visits and another with 5. Call use() three times on the first and print each result, then print both left() values. Expected:

Text
true
true
false
0
5

The count must never go below 0, and main must not touch the field directly.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Create two passes, use the first three times, then report both.
    }
}

class Pass {
    // Define private state, a constructor and the two public methods.
}
Hint 1: the idea

use() has a rule to protect: the visits left can't go below zero. Like the Budget example above, check the rule before changing anything.

Hint 2: a first step

Start use() with if (visits == 0) and return false inside it. Only after that check, subtract one and return true. The third call should print false.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        Pass first = new Pass(2);
        Pass second = new Pass(5);

        System.out.println(first.use());
        System.out.println(first.use());
        System.out.println(first.use());

        System.out.println(first.left());
        System.out.println(second.left());
    }
}

class Pass {
    private int visits;

    Pass(int visits) {
        this.visits = visits;
    }

    public boolean use() {
        if (visits == 0) {
            return false;
        }

        visits--;
        return true;
    }

    public int left() {
        return visits;
    }
}
Text
true
true
false
0
5

The check if (visits == 0) comes before visits--, so a refused visit changes nothing: left() is 0, not −1. Because visits is private, use() is the only way to change it, so no caller can skip that check. second still has 5 because each Pass object has its own field.

Change it and explain

Move visits-- above the check in use() so it subtracts first. Predict the five printed lines, then run it. Then add a topUp(int extra) method that refuses negative amounts, and decide whether it belongs in the brief or is an optional extension: a smaller API can be easier to understand and test.

Use methods to enforce meaningful rules, not just to disguise arbitrary assignment. A complete() method communicates more intent than setDone(boolean) when the project never needs to make a completed session incomplete.

Was this article helpful?

Your response is saved on this device.