devnotes.

Abstraction vs. Encapsulation

Beginners often confuse abstraction and encapsulation because they work together and frequently look similar in code. A clear way to separate them:

  • Encapsulation is a mechanism — the technical act of bundling data with methods and restricting direct access (via private, protected, getters/setters). It answers: 'How do I protect this data?'
  • Abstraction is a design principle — deciding what to show and what to hide at a conceptual level, independent of any specific access-control keyword. It answers: 'What does the outside world actually need to know?'

Example that shows the difference:

interface Shape {
    function area(): number
}

class Circle implements Shape {
    private radius

    function __construct(radius) { this.radius = radius }

    function area(): number {
        return 3.14159 * this.radius * this.radius
    }
}
  • The Shape interface is abstraction: it defines what any shape can do (area()) without saying how, letting calling code work with any shape uniformly.
  • The private radius and the specific formula inside area() are encapsulation: the internal data and calculation are hidden and protected from outside interference.

A useful mental shortcut: encapsulation is about access (can you reach the data directly?); abstraction is about complexity (do you need to understand how it works to use it?). You can have encapsulation without much abstraction (a class with private fields but a messy, low-level public API), and in principle you can have some abstraction without strict encapsulation — though in practice, well-designed OOP code almost always combines both.

Abstraction vs Encapsulation: What's the Difference? | DevNotes