Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

0.2 Abstraction and Encapsulation

How it works

Abstraction hides how something is done behind what it does. Encapsulation is the mechanism: private state, public behavior.

Expose the smallest interface that lets callers do their job, and keep representation private.

Common error

Leaking the representation through a getter, which freezes the implementation permanently.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

class Meter {
    private int value;
    void add(int amount) { if (amount > 0) value += amount; }
    int read() { return value; }
}
Meter m = new Meter();
m.add(4); m.add(-2);
System.out.println(m.read());

Output

4

Private state and a small public-facing operation protect the invariant that this meter only increases. Callers request behavior rather than editing the field directly.

Exercises

0.2.1 · Explain

Why can returning an internal mutable list from an accessor weaken encapsulation?

Show solution

The caller may alter the same list and bypass the class validation. Return an appropriate defensive copy or controlled view when independent mutation must not be allowed.

0.2.2 · Write code

Create a Counter with a private count and an increment method, then show two increments.

Show solution

Keep mutation inside the class.

One valid solution

class Counter {
    private int count;
    void increment() { count++; }
    int getCount() { return count; }
}
Counter c = new Counter(); c.increment(); c.increment();
System.out.println(c.getCount());

Expected output

2
Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic