Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 57 ยท Getting Started with Design

OOP Foundations for Design

Review encapsulation, abstraction, inheritance and polymorphism with a design focus. Compare interfaces and abstract classes across Java, C++, Python and JavaScript.

Design patterns are built from four old ideas: encapsulation, abstraction, inheritance and polymorphism. If those ideas are fuzzy, patterns feel like magic recipes. If they are sharp, patterns look like obvious consequences. This lesson reviews the four with a design eye: not "what is the syntax" but "what does each one let me change safely".

You can learn the syntax in the language tutorials. For Java, see encapsulation, inheritance, polymorphism, interfaces and abstract classes. Here we focus on how the four ideas interact and how they differ between Java, C++, Python and JavaScript.

Java, C++ and Python class code in this lesson is mostly read-only to show how each language spells the idea. The runnable examples are JavaScript (browser console and Node on the server runner), which stand in for the same structures.

Four ideas, one goal

Encapsulation Hide state behind methods.
Abstraction Show what, hide how.
Inheritance Reuse and specialize.
Polymorphism One call, many behaviors.
1 / 2

Encapsulation: protect the invariants

Encapsulation means an object keeps its data private and exposes behavior. The reason is not secrecy. It is that an object can promise rules (invariants) only if nobody else can break them. A bank account that promises "balance never goes negative" can keep that promise only if outsiders cannot assign to balance directly.

Java
public class Account {
    private double balance;

    public void withdraw(double amount) {
        if (amount <= 0 || amount > balance) {
            throw new IllegalArgumentException("invalid amount");
        }
        balance -= amount;
    }
    public double getBalance() { return balance; }
}

JavaScript has real private fields, written with #. This runs in the browser.

JS Encapsulation with private fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Python has no true private members; a leading underscore (_balance) is a convention that says "do not touch". C++ has private: enforced by the compiler. These differences matter: in Python, encapsulation relies on discipline and code review, so patterns that protect state (like immutability) are used more.

Abstraction: depend on what, not how

Abstraction means exposing a simple contract and hiding the machinery. A Logger with a log(message) method is an abstraction: callers do not know whether it writes to a file, a console or a network service. The key design move is that callers depend on the contract, not the implementation, so you can replace the implementation later.

Abstraction and encapsulation are often confused. Encapsulation protects an object's data. Abstraction chooses what interface to present. A well-designed class has both, but you can have one without the other: a public field in a class with a clean interface has abstraction but no encapsulation.

Inheritance: specialization, with a warning

Inheritance lets one class build on another. A SavingsAccount is an Account with an interest rule added. It gives you code reuse and a subtype relationship (you can use a SavingsAccount wherever an Account is expected).

The warning: inheritance is the tightest coupling you can create between two classes. A subclass depends on the parent's internal behavior, not just its public contract, so a change in the parent can break the child. Because of this, modern design often prefers composition (holding another object and delegating) over inheritance. You will see this again in beyond SOLID. Use inheritance for a genuine is-a relationship that follows the Liskov Substitution Principle, and prefer composition for has-a or uses-a.

Polymorphism: one call, many behaviors

Polymorphism means the same call does different things depending on the actual object. This is what makes patterns like Strategy, State and Command work: the caller says shape.area() and does not care which shape it holds.

JS Polymorphism and the open-ended list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

describe() is defined once in Shape and calls this.area(), which runs the subclass version. That mix of a shared method calling an overridable one is the seed of the Template Method pattern.

Interfaces versus abstract classes

Both define a contract that other classes fulfill. They differ in what they may carry.

Interface Abstract class
Instances Cannot be created Cannot be created
State (fields) None (constants only in Java) Yes
Constructors No Yes
Inheritance A class may implement many A class extends only one (Java, C#)
Typical role A capability or role ("can be sorted") A partial base ("is a kind of X, with shared code")

A good habit: start with an interface, because it forces callers to depend on the contract. Add an abstract base class only when several implementations share real code. Java and C# have both concepts. C++ has no interface keyword; the equivalent is a class with only pure virtual functions. Python uses abc.ABC for abstract classes and typing.Protocol for structural interfaces. JavaScript has neither: you write a convention and check it at runtime.

C++
// C++: an "interface" is a class of pure virtual functions
struct Logger {
    virtual ~Logger() = default;       // always give interfaces a virtual destructor
    virtual void log(const std::string& message) = 0;
};
Python
from abc import ABC, abstractmethod

class Logger(ABC):                     # Python: abstract base class
    @abstractmethod
    def log(self, message: str) -> None: ...

Object relationships: association, aggregation and composition

Inheritance is one way classes relate. The other, and far more common, is has-a: one object holds a reference to another. The three has-a flavors differ in one question, who controls the lifetime of the part? The UML lesson shows how to draw them; here is how they look in code.

  • Association: object A knows object B and uses it, but neither owns the other. A Customer places Orders; both live independently, and the link is a reference.
  • Aggregation: a whole that groups parts which exist on their own. A Team has Players, yet a player stays in the league if the team folds. The parts are created outside the whole and handed in.
  • Composition: a whole that owns its parts. An Order creates its OrderLines, nobody outside should hold them, and when the order goes, they go. The parts are created inside the whole and are not shared.

You can read the difference straight from the constructor: parts that arrive as arguments and are stored point to aggregation, and parts that the class news itself and never hands out point to composition.

JS Aggregation versus composition in code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The team never creates players and does not control them; the order creates its lines and never lets the real objects escape. That protection is encapsulation doing the work that composition promises.

Choosing between the three affects design in practical ways:

  • Prefer composition over inheritance for reuse, as in Strategy and Decorator: a has-a link can be swapped at run time, an is-a link cannot.
  • Use composition when the part has no meaning alone (a line item, an address inside a customer record). Cascade deletes, copy it with the whole, and keep it private.
  • Use aggregation when parts are shared or long-lived (players, products in several catalogs). Deleting the group must not delete the parts.
  • Use plain association for collaborators that are found, not owned (a service looking up a repository).
  • The lifetime line is a business decision, not a language rule. In a garbage-collected language nothing is physically destroyed by the whole; ownership means "this is the only place that should refer to it".

Abstraction versus encapsulation, once more

These two are the most mixed-up words in object-oriented design.

Abstraction Encapsulation
Question What should the outside see? How do I protect what is inside?
Works on Design: choosing the interface Implementation: restricting access
Mechanism Interfaces, abstract classes, good naming Private members, defensive copies, immutability
Example Shape.area() hides the formula #lines cannot be changed from outside
Failure A leaky interface that exposes internals A public field that anyone can corrupt

In the examples above, Order.total() is abstraction (callers ask for a total, not how it is computed), and the private #lines with the copying lines() method is encapsulation (the parts cannot be damaged). A good class has both.

Language differences that change design

Idea Java C++ Python JavaScript
Private members private, enforced private:, enforced _name by convention #name, enforced
Interfaces interface Pure virtual class Protocol or ABC Convention, duck typing
Multiple inheritance Interfaces only Allowed (with care) Allowed Single, plus mixins
Method dispatch Virtual by default Virtual only if declared Always dynamic Always dynamic
Memory Garbage collected Manual or RAII Garbage collected Garbage collected

Two consequences. First, in dynamic languages (Python, JavaScript), polymorphism does not need a shared base class at all: any object with the right method works. This is called duck typing. Second, in C++ polymorphism through a base-class pointer needs virtual, and deleting through a base pointer needs a virtual destructor, or the derived part is not cleaned up.

Duck typing on the server runner

The following Node stand-in shows polymorphism without any inheritance. Two unrelated classes both have send(text), so the notifier works with either.

Node.js Duck typing: no shared base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The honest trade-off: duck typing is flexible and short, but a typo in a method name fails at runtime instead of at compile time. TypeScript and Python's Protocol add static checks on top of the same idea.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main design reason for encapsulation?

    Encapsulation lets a class protect its invariants. A balance that cannot go negative stays valid only if no outside code can assign it directly.
  2. 2. Why do many designers prefer composition over inheritance when both would work?

    A subclass depends on its parent's internals, so parent changes can break it. Delegating to a held object depends only on a public contract.
  3. 3. Which statement about interfaces and abstract classes is correct for Java?

    Abstract classes can carry state and constructors; interfaces cannot. A Java class extends one class but may implement many interfaces.
  4. 4. In JavaScript, how can two unrelated classes both be used by the same function that calls channel.send(text)?

    Duck typing means any object with the needed method works, without a declared shared type.
  5. 5. In C++, what must you add to a base class so that deleting a derived object through a base pointer is safe?

    Without a virtual destructor, deleting through a base pointer skips the derived destructor, which is undefined behavior.

Summary

  • Encapsulation protects an object's invariants by hiding its data behind behavior.
  • Abstraction chooses the contract callers depend on, so implementations can change.
  • Inheritance gives reuse and subtyping but is the tightest coupling; use it for true is-a relationships.
  • Polymorphism lets one call run different code depending on the object, and it powers most patterns.
  • Prefer starting with an interface; add an abstract class only for shared code.
  • Java, C++, Python and JavaScript differ in privacy, interfaces and dispatch, which changes how much of a pattern you need to write.

Next, the five principles that guide how these tools should be combined: SOLID at a Glance.