Skip to main content
Be Bitwise

Encapsulation & Interfaces

Classes & Object-Oriented Programming · Coding Fundamentals track

8 min read

In this module

Hiding the Details

Picture yourself driving a car. You press the accelerator and the car speeds up. You don't need to understand fuel injection, valve timing, or combustion chemistry. The car exposes a simple interface (pedals, steering wheel, gear shift) and hides the messy internals.

Encapsulation is the same principle, applied to software. A class exposes a public interface — methods external code can call — and hides its internal data and implementation. The outside world only ever interacts with the object through that controlled interface.

Public and Private

Most object-oriented languages let you mark fields and methods as public (accessible from anywhere) or private (accessible only from within the class).

text
class TemperatureSensor {
private raw_reading // internal detail
private calibration // internal detail
constructor(calibration) {
this.calibration = calibration
this.raw_reading = 0
}
private function apply_calibration(raw) {
return raw * this.calibration + 0.5
}
public function read_temperature() {
this.raw_reading = hardware_read()
return this.apply_calibration(this.raw_reading)
}
}

External code can only call read_temperature(). It cannot touch raw_reading, calibration, or apply_calibration directly. That's deliberate. If the calibration formula changes tomorrow, nothing on the outside breaks, because nothing on the outside depended on it.

Key Concept

Encapsulation means bundling data with the methods that operate on it, and controlling access so that internal details are hidden. This protects the object's integrity and lets you change internals without breaking external code.

Why Encapsulation Matters

Strip out encapsulation and any code anywhere can reach in and modify an object's state. The result is brittle programs where a change in one place causes mysterious breakage somewhere else entirely.

text
// Without encapsulation - dangerous
account.balance = -9999 // Oops, set a negative balance directly
// With encapsulation - safe
account.withdraw(9999) // The method checks and rejects invalid amounts

Encapsulation enforces invariants — conditions that should always hold. A bank account's balance should never go negative (unless the bank allows overdrafts). Make balance private and only let deposit and withdraw modify it, and the class guarantees the invariant.

Getters and Setters

Sometimes you want to permit controlled access to a private field. Getters return the value; setters change it — and a setter can include validation logic on the way in.

text
class Rectangle {
private width
private height
function get_width() {
return this.width
}
function set_width(value) {
if value <= 0 {
print("Width must be positive")
return
}
this.width = value
}
function area() {
return this.width * this.height
}
}

The getter provides read access. The setter provides write access with validation - you cannot set a negative width. That's a finer-grained form of access control than just making the field public.

Interfaces and Contracts

An interface defines a set of methods a class must implement, without specifying how. It's a contract: "implement this interface and you've promised to provide these methods."

text
interface Shape {
function area()
function perimeter()
}
class Circle implements Shape {
radius
function area() {
return 3.14159 * this.radius * this.radius
}
function perimeter() {
return 2 * 3.14159 * this.radius
}
}
class Rectangle implements Shape {
width
height
function area() {
return this.width * this.height
}
function perimeter() {
return 2 * (this.width + this.height)
}
}

Both Circle and Rectangle implement the Shape interface. Any code that works with a Shape can swallow either one without knowing or caring which specific shape it has. That's a powerful form of abstraction.

Drawn as a class diagram, the contract sits on top and the dotted arrows mean "implements". Notice what the interface box doesn't have: no fields at all. The radius, width and height stay private to each class, so callers can only ever reach them through area() and perimeter().

The + and - marks are the usual shorthand for public and private.

Information Hiding in Systems

Encapsulation is a design principle that surfaces all over computing, well beyond OOP:

  • System calls hide kernel internals behind a clean API. Your program calls read() without ever needing to know how the file system works inside.
  • Hardware interfaces expose registers and commands and tuck the transistor-level details out of sight.
  • Network protocols expose request/response interfaces and conceal routing, packet fragmentation, and error correction.

The pattern is the same every time: a simple, stable interface on the outside, complex and shifting details locked inside. That separation of concerns is what makes building systems of huge complexity tractable at all.

The Cost of Over-Encapsulation

A word of caution: encapsulation is a tool, not a religion. Making everything private and wrapping every field in getters and setters drowns the codebase in boilerplate. The point is to guard meaningful invariants and hide genuinely complex internals, not to add ceremony for its own sake. Good encapsulation boundaries fall out from understanding which details are likely to shift and which should hold steady.

Encapsulation at the Hardware Level

At the machine level, "private" doesn't exist. All memory is fair game if you have the address. Encapsulation is enforced by the compiler, which refuses to emit code that accesses private fields from outside the class. (Java and C# also let reflection reach past private at runtime.) In languages without access modifiers (C is the obvious example), encapsulation is a convention: hide internals in .c files, expose only the public API in .h headers.

The program below squeezes both halves of that pattern into one file. main sits between the "header" and the "implementation", so it only knows that struct account exists, not what's inside it. Uncomment the first marked line and the compiler refuses to build it. Uncomment the second, and raw memory access walks straight past the invariant.

Try itTry each commented-out line in main on its own: one fails to compile, the other compiles and breaks the rule.
C (GCC 9.2.0)

Once you grasp that encapsulation is a compile-time contract, not a runtime guard, you start to appreciate its power as a design tool and its limits as a security mechanism.