Skip to content
Chethan Yadav_
Object-Oriented Programming

OOP/Lesson 2 of 5/6 min read

The Four Pillars

Encapsulation, abstraction, inheritance and polymorphism, with overloading vs overriding, dynamic dispatch and abstract classes vs interfaces.


On this page

The four pillars at a glance

PillarOne-line meaningMechanism
EncapsulationHide internal state, expose controlled operationsAccess modifiers
AbstractionShow what an object does, hide howInterfaces, abstract classes
InheritanceA class reuses and extends anotherextends, :
PolymorphismOne interface, many implementationsOverloading, overriding

Encapsulation

Bundling data with the methods that operate on it, and restricting direct access to the data. The object guards its own invariants.

class Temperature {
    private double celsius;
 
    public void setCelsius(double c) {
        if (c < -273.15) throw new IllegalArgumentException("below absolute zero");
        this.celsius = c;
    }
    public double getFahrenheit() { return celsius * 9 / 5 + 32; }
}

Benefits: invalid states are impossible from outside, internals can change without breaking callers, and debugging is easier because state changes go through one place.

Abstraction

Exposing only essential features and hiding implementation details. A driver uses the steering wheel and pedals without knowing how the engine works. List.add() hides whether it is an array or a linked list.

Encapsulation vs abstraction: abstraction is a design idea (what to expose); encapsulation is the implementation tool (how to hide the rest).

Inheritance

A subclass (child) acquires fields and methods of a superclass (parent) and can add or override behavior. Models an is-a relationship: a Dog is an Animal.

class Animal {
    protected String name;
    void speak() { System.out.println("..."); }
}
 
class Dog extends Animal {
    @Override
    void speak() { System.out.println(name + " says woof"); }
}

Types of inheritance

TypeShapeSupported in
SingleA to BAll
MultilevelA to B to CAll
HierarchicalA to B, A to CAll
MultipleA and B to CC++, Python (Java and C# only via interfaces)
HybridMix of the aboveC++, Python

Diamond Problem

B and C both extend A and override foo(); D extends both B and C. Which foo() does D get?

  • Java and C# avoid it by disallowing multiple class inheritance. With default methods in two interfaces, the class must override explicitly.
  • C++ uses virtual inheritance to share one A subobject.
  • Python uses the method resolution order (C3 linearization); inspect with D.__mro__.

Pitfalls of inheritance

  • Tight coupling: changes in the parent ripple into every child (fragile base class).
  • Deep hierarchies are hard to understand.
  • Using inheritance for code reuse when there is no real is-a relationship. Prefer composition (has-a); see advanced OOP.

Polymorphism

"Many forms": the same call behaves differently depending on the type.

Method Overloading

Compile-time (static) polymorphism: same method name, different parameter lists, in the same class.

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }

The return type alone cannot distinguish overloads. Python has no true overloading (the last definition wins); use default arguments or functools.singledispatch.

Method Overriding

Runtime (dynamic) polymorphism: a subclass provides its own implementation of a parent method with the same signature.

Animal a = new Dog();
a.speak();   // "woof": decided at runtime by the actual object type

Rules (Java): same name and parameters; return type same or covariant (a subtype); access cannot be more restrictive; cannot throw broader checked exceptions; static, final and private methods cannot be overridden.

OverloadingOverriding
WhereSame classParent and child
SignatureDifferent parametersSame parameters
ResolvedCompile timeRuntime
Also calledStatic polymorphismDynamic polymorphism

Dynamic Dispatch

How runtime polymorphism works. In C++ and Java, each class with virtual methods has a vtable (table of function pointers), and each object holds a hidden pointer to its class's vtable. A virtual call looks up the method in the vtable at runtime.

  • In Java, all non-static, non-final, non-private methods are virtual by default.
  • In C++, only methods marked virtual are. Forgetting virtual on a base destructor leaks resources when deleting through a base pointer.

Abstract Class

A class that cannot be instantiated and may contain both implemented and abstract (unimplemented) methods. Subclasses must implement the abstract ones.

abstract class Shape {
    abstract double area();
    void describe() { System.out.println("Area: " + area()); }  // template
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}

Interface

A pure contract: a set of method signatures a class promises to implement. A class can implement many interfaces.

interface Payable { void pay(double amount); }
interface Refundable { void refund(String txId); }
class CardPayment implements Payable, Refundable { ... }

Since Java 8, interfaces can have default and static methods; since Java 9, private helpers.

Abstract class vs interface

Abstract classInterface
InstantiableNoNo
State (instance fields)YesNo (only constants)
ConstructorsYesNo
Multiple inheritanceNo (one parent)Yes (many interfaces)
MethodsAbstract and concreteAbstract, default, static
Relationshipis-a, shared base codecan-do capability
Use whenRelated classes share code and stateUnrelated classes share a capability
Interview tip: say "program to an interface, not an implementation". Declare variables as List, not ArrayList, so the concrete class can change without touching callers.

Quick revision

  • Encapsulation hides state behind methods and protects invariants.
  • Abstraction exposes what, hides how; encapsulation is the tool that enforces it.
  • Inheritance is is-a; beware fragile base classes and prefer composition for reuse.
  • Diamond problem: Java forbids multiple class inheritance, C++ uses virtual inheritance, Python uses MRO.
  • Overloading: same name, different parameters, compile time. Overriding: same signature in subclass, runtime.
  • Dynamic dispatch uses vtables; make C++ base destructors virtual.
  • Abstract class shares code and state; interface defines a capability and allows multiple implementation.