Skip to content
notes.vinhnq.com

Search

OOP & DesignMid20 min read

Object-oriented programming: inheritance, encapsulation and polymorphism

Review 19 cards
On this page

Object-oriented programming series: 1. Classes, objects, access modifiers · 2. Immutability, equals/hashCode, final · 3. Inheritance, encapsulation, polymorphism · 4. Abstract classes and interfaces · 5. UML, class relationships · 6. Wrappers, BigDecimal, String

Inheritance reuses code, polymorphism lets you add a new kind of thing without touching old code, and encapsulation keeps every object valid; misused, deep hierarchies turn fragile and business logic scatters everywhere. After this post you can explain extends/super/@Override, how the JVM picks a method at runtime, and the traps interviewers like. Read part 1 first (classes, constructors, access modifiers); abstraction and object initialization order are in part 4.

1. The four pillars of OOP

Key idea: OOP rests on four pillars: encapsulation, inheritance, polymorphism and abstraction. This post covers the first three; abstraction (abstract classes, interfaces) is in part 4.

flowchart LR
  OOP((OOP)) --> E[Encapsulation<br/>hide state, expose behavior]
  OOP --> I[Inheritance<br/>reuse, is-a]
  OOP --> P[Polymorphism<br/>one call, many implementations]
  OOP --> A[Abstraction<br/>expose only what matters]

2. Inheritance

Key idea: a subclass is built by extending an existing superclass, in an “is-a” relationship: a Dog is an Animal. Java allows only one parent class, and inheritance should be used sparingly.

class Animal {
    private final String name;
    protected Animal(String name) { this.name = name; }
    public String name() { return name; }
    public String sound() { return "..."; }
}

class Dog extends Animal {
    private final String breed;

    Dog(String name, String breed) {
        super(name);                 // must be the first statement in the constructor
        this.breed = breed;
    }

    @Override
    public String sound() { return "Woof"; }

    public String describe() {
        return name() + " (" + breed + ") says " + sound() + "; its parent says " + super.sound();
    }
}
Rule Detail
super(...) / super.method() Calls the parent constructor / the parent’s version of a method. Leave it out and the compiler inserts a no-arg super(), which fails to compile if the parent has no such constructor.
this Refers to the current object.
The parent’s private fields Still exist inside the subclass object, but the subclass can’t touch them directly; it goes through public/protected methods.
Single inheritance A class extends only one class (avoiding the “diamond problem”) but can implements many interfaces. Every class implicitly extends java.lang.Object.
Constructors Not inherited: a subclass declares its own and calls the right super(...).
static members Inherited (reachable through the subclass name) but not polymorphic.
final A final class (like String) can’t be extended; a final method can’t be overridden.

Since Java 25 (JEP 513) you may put some statements before super(...), for example argument validation, as long as they don’t touch this.

The slides say “don’t extend classes casually”, and they’re right. Here is why:

Example: the quadrilateral tree and the limits of “is-a”

Key idea: the geometry tree is mathematically correct, but a mathematical “is-a” isn’t enough for a safe class hierarchy. Math talks about properties of shapes; classes also carry behavior, especially state-changing behavior.

The slides draw: the quadrilateral is the root; a parallelogram is a quadrilateral; rectangles and rhombuses are parallelograms; a square is a rectangle. Redrawn as a UML class diagram:

classDiagram
  direction BT
  class Quadrilateral
  class Parallelogram
  class Rectangle
  class Rhombus
  class Square
  Quadrilateral <|-- Parallelogram
  Parallelogram <|-- Rectangle
  Parallelogram <|-- Rhombus
  Rectangle <|-- Square

Arrows go from the subclass up to the parent, with a hollow triangle touching the parent: the child knows its parent, the parent doesn’t know its children.

The safe version: sealed interface and records (run on JDK 21)
sealed interface Shape permits Rect, Sq { double area(); }

record Rect(double width, double height) implements Shape {
    public double area() { return width * height; }
    Rect withWidth(double w) { return new Rect(w, height); }   // returns a new object
}

record Sq(double side) implements Shape {
    public double area() { return side * side; }
    Rect asRect() { return new Rect(side, side); }             // to "stretch" it, convert to a Rect
}

Sq sq = new Sq(3);
Rect wider = sq.asRect().withWidth(5);
System.out.println(sq.area() + " " + wider.area());          // 9.0 15.0, and sq is unchanged

3. Encapsulation

Key idea: encapsulation means hiding internal state and letting the outside affect it only through controlled methods. That way the object always upholds its invariants (rules that must always hold, such as “the balance never goes negative”).

The slides’ example: every shape computes its area differently, so that logic should belong to each shape’s own class, not to an outside if (shape is Circle) ... else if (shape is Square) ... chain. That leads straight to polymorphism.

4. Polymorphism

Key idea: the same method call behaves differently depending on the object, so one piece of code works for many kinds of objects. It comes in two forms: overloading (picked at compile time) and overriding (picked at runtime).

Overloading Overriding
Kind Compile-time (static) Runtime (dynamic dispatch)
Where Same class, or a subclass adding another variant A subclass redefines a parent or interface method
Signature Same name, different parameter lists Same name and parameters; return type identical or a subtype (covariant)
Chosen by The declared types of the arguments The actual runtime type of the object
static/private/final Can be overloaded Can’t be overridden

Compile time is when javac (and your IDE’s red squiggles) checks types; runtime is when the JVM executes the bytecode. Overload selection, calling a missing method and assigning the wrong type are caught by the compiler; a bad downcast or a null only shows up at runtime (see the three kinds of errors in Java basics).

abstract class Shape {
    abstract double area();
}
class Circle extends Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}
class Rect extends Shape {
    private final double w, h;
    Rect(double w, double h) { this.w = w; this.h = h; }
    @Override double area() { return w * h; }
}

List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3));
double total = 0;
for (Shape s : shapes) total += s.area();   // the JVM picks area() by each object's real type

Add a Triangle and that loop doesn’t change. That is the Open/Closed Principle: open for extension, closed for modification.

Override rules worth remembering (a few of which the slides get slightly wrong):

  • Per the Java spec, a signature is just the name plus the parameter types. The return type isn’t part of it, but an override must return the same type or a subtype (covariant return).
  • An override can’t narrow access (a public parent method can’t become protected) and can’t throw broader checked exceptions.
  • Always add @Override: misspell the name or parameters and the compiler complains instead of silently creating an overload.
  • private methods can’t be overridden, because subclasses can’t see them.
Overload resolution rules and dynamic dispatch under the hood

Upcasting, downcasting and instanceof

Key idea: the declared type (left of =) decides which methods you’re allowed to call; the runtime type (the class of the object on the heap) decides which version runs. Upcasts are always safe; a wrong downcast throws ClassCastException at runtime.

class Animal {
    String sound() { return "..."; }
}
class Dog extends Animal {
    @Override String sound() { return "Woof"; }
    void wagTail() { System.out.println("wagging"); }
}
class Cat extends Animal { }

Animal a = new Dog();     // upcast: always safe, no cast needed
a.sound();                // "Woof": the runtime type picks the version
// a.wagTail();           // compile error: the declared type Animal has no wagTail

Dog d = (Dog) a;          // downcast: must be explicit; the compiler takes your word for it
d.wagTail();              // fine, because the object really is a Dog

Animal c = new Cat();
Dog x = (Dog) c;          // compiles, but throws ClassCastException at runtime
  • An upcast (child → parent) is always valid, which is what lets a List<Shape> hold every kind of shape.
  • A downcast (parent → child) is only correct when the object really is that subclass. Casting null to any type never fails; you just get null.
  • Casting between unrelated branches ((String) dog) is rejected by the compiler straight away.
  • x instanceof T returns false when x is null, so no separate null check is needed.

Since Java 16 (JEP 394), instanceof supports pattern matching: test and cast in one step, with the variable in scope only where the condition is definitely true.

if (a instanceof Dog dog) {           // no separate Dog dog = (Dog) a; line
    dog.wagTail();
}
if (!(o instanceof String s)) return; // negated: s is usable from here on
if (o instanceof String s && s.length() > 3) { ... }   // usable right inside the && condition
Fields aren’t polymorphic: a field-hiding example

Exercises

Each prompt is a short paraphrase. All solutions were run on JDK 21.

1. Lab 05: Person → Employee → Manager

Task (paraphrased): three classes in a chain.

  • Person: a name, an age, a constructor, getters/setters and a method that introduces the person.
  • Employee extends Person: adds an employee id and a salary; its constructor calls super(name, age); it overrides the introduction to also print the id and salary; two salary methods: without arguments it returns the salary, with a bonus argument it returns salary plus bonus.
  • Manager extends Employee: adds a department and overrides the introduction while reusing the parent’s version.
  • main: create a 25-year-old manager with id M001, salary 2000, department Sales; call the introduction and both salary methods (bonus 500).
Lab 05 solution and a senior’s review
import java.math.BigDecimal;
import java.util.Objects;

public class Lab05 {
    static class Person {
        private final String name;
        private int age;

        Person(String name, int age) {
            this.name = Objects.requireNonNull(name, "name");
            setAge(age);
        }

        public String getName() { return name; }
        public int getAge() { return age; }
        public void setAge(int age) {
            if (age < 0) throw new IllegalArgumentException("age must be >= 0");
            this.age = age;
        }

        public void introduce() {
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
        }
    }

    static class Employee extends Person {
        private final String employeeId;
        private final BigDecimal salary;

        Employee(String name, int age, String employeeId, BigDecimal salary) {
            super(name, age);                                  // must be the first statement
            this.employeeId = Objects.requireNonNull(employeeId, "employeeId");
            if (salary.signum() < 0) throw new IllegalArgumentException("salary must be >= 0");
            this.salary = salary;
        }

        public String getEmployeeId() { return employeeId; }

        @Override
        public void introduce() {
            super.introduce();                                 // reuse Person's output
            System.out.println("Employee ID: " + employeeId);
            System.out.println("Salary: " + salary);
        }

        public BigDecimal calculateSalary() {                  // overload 1
            return salary;
        }

        public BigDecimal calculateSalary(BigDecimal bonus) {  // overload 2: different parameter list
            if (bonus.signum() < 0) throw new IllegalArgumentException("bonus must be >= 0");
            return calculateSalary().add(bonus);               // call the no-arg version so a subclass override still applies
        }
    }

    static class Manager extends Employee {
        private final String department;

        Manager(String name, int age, String employeeId, BigDecimal salary, String department) {
            super(name, age, employeeId, salary);
            this.department = department;
        }

        @Override
        public void introduce() {
            super.introduce();                                 // Employee.introduce -> Person.introduce
            System.out.println("Department: " + department);
        }
    }

    public static void main(String[] args) {
        Manager m = new Manager("Lan", 25, "M001", new BigDecimal("2000"), "Sales");
        m.introduce();
        System.out.println("Base salary: " + m.calculateSalary());
        System.out.println("Salary with bonus: " + m.calculateSalary(new BigDecimal("500")));

        Person p = m;                                          // upcast
        p.introduce();                                         // still runs Manager's version
    }
}
Name: Lan
Age: 25
Employee ID: M001
Salary: 2000
Department: Sales
Base salary: 2000
Salary with bonus: 2500
(p.introduce() prints the same five lines again)

What to notice:

  • super(name, age) must be the first statement. Person has no no-arg constructor, so leaving this line out is a compile error (the compiler only inserts an implicit no-arg super()).
  • super.introduce() forms a chain Manager → Employee → Person: each level prints only its own part, with no copied code.
  • The two calculateSalary methods are overloads (different parameters, chosen at compile time). introduce is an override (chosen at runtime), so Person p = m; p.introduce() still prints the department.
  • calculateSalary(bonus) calls calculateSalary() instead of reading the salary field directly. If a subclass overrides the base calculation (say a manager gets 110%, as in another overriding exercise in the material), the bonus version stays correct automatically.

A senior reviewer’s notes:

  • Person → Employee → Manager is the textbook example and often wrong in real life. “Manager” is a role that can change (promotions), not a fixed type. Java can’t change the class of a live object, so a promotion means creating a new object and losing its identity.
  • A sturdier design gives Employee a Position or Role field (composition, see part 5).
  • introduce() prints straight to the console, mixing logic with presentation; returning a String or overriding toString() makes it testable.
  • Salaries are BigDecimal, and a negative bonus is rejected.

Remember

  • Explain why composition is preferred, with the InstrumentedSet and Stack extends Vector examples.
  • Explain why Square extends Rectangle breaks Liskov, and when it becomes acceptable.
  • Tell overloading from overriding: when each is picked and by which type; and why statics and fields are only hidden.
  • Know what the declared type and the runtime type each decide, and when a downcast is safe.
  • Know the order in which the compiler picks an overload (widening → boxing → varargs) and the list.remove(1) trap.

Interview questions

Junior

What are the four pillars of OOP? Give an example of each.

Encapsulation, inheritance, polymorphism and abstraction.

  • Encapsulation: Account.withdraw() checks the balance itself.
  • Inheritance: Dog extends Animal.
  • Polymorphism: shape.area() runs the version matching the object’s real type.
  • Abstraction: code depends on a PaymentGateway interface without knowing whether Stripe or VNPay sits behind it.
Does Java support multiple inheritance? What is super for?

Not for classes: a class can extend only one class, but it can implement many interfaces. super calls the parent’s constructor or methods.

Single inheritance avoids the “diamond problem” when two parents carry conflicting state or implementations. super(...) must be the first statement of a constructor; leave it out and the compiler inserts a no-arg super(). super.method() calls the parent’s version from inside an override. Constructors aren’t inherited, so a subclass always declares its own.

Mid

What is the difference between overloading and overriding? Can static methods be overridden?

Overloads are picked at compile time from the arguments’ declared types; overrides at runtime from the object’s actual type. Static methods can’t be overridden, only hidden.

Overloading means the same name with different parameters. Overriding means a subclass redefines a method with the same signature. With statics (hiding), which one runs depends on the variable’s declared type.

Given Animal a = new Dog();, which methods can a call? When is a downcast safe?

The declared type Animal decides what you can call, the runtime type Dog decides which version runs. A downcast is safe only when the object really is the target type.

a can’t call Dog’s own wagTail(), but a.sound() runs Dog’s version. Fields aren’t polymorphic: a.name reads the field declared in Animal. A wrong downcast throws ClassCastException; check with instanceof, or since Java 16 write if (a instanceof Dog d). instanceof on null returns false.

When several overloads match a call, which one does the compiler pick?

Three phases: exact match or widening, then boxing/unboxing, then varargs; within a phase, the most specific method wins.

  • m(long) and m(Integer): m(5) calls m(long).
  • n(Object) and n(String): n(null) calls n(String).
  • p(String) and p(Integer): p(null) is an ambiguity error.

All of this uses the declared types of the arguments, not their runtime types, and you can’t overload on the return type alone.

Senior

What does “favor composition over inheritance” mean? Give an example of inheritance causing harm.

Inheritance ties a subclass to its parent’s implementation details (fragile base class); composition depends only on the public API, so it’s more flexible.

  • A counting subclass of HashSet double-counts because addAll calls add internally.
  • Stack extends Vector exposes methods that break LIFO.

Composition (wrapping an object and delegating to it) can also be swapped at runtime. Inherit only for a real is-a relationship that respects the Liskov Substitution Principle.

How does dynamic dispatch work in the JVM? Is it expensive?

The JVM looks up the vtable/itable for the object’s actual class, and the JIT inlines call sites that see few types, so it’s rarely a bottleneck.

Instance calls use invokevirtual/invokeinterface. The JIT profiles each call site: monomorphic (one type) and bimorphic (two types) sites get inlined behind a cheap type check. Only megamorphic sites pay for a real table lookup.

A square is a rectangle in geometry. So what’s wrong with Square extends Rectangle, and when is it acceptable?

LSP requires a subclass to honor every behavioral contract of its parent, and Square can’t honor “width and height change independently”. It’s acceptable once shapes are immutable.

Changing a Square’s height also changes its width, so code written against Rectangle gets wrong results. If shapes are immutable (no setters, changes return new objects), the contract shrinks to reads like area(), which a square satisfies. In practice I usually prefer a sealed interface Shape with sibling records: simpler, and a switch over it is checked for exhaustiveness.

Useful phrases for interviews

  • “Encapsulation isn’t about getters and setters; it’s about putting the behavior next to the data it protects.”
  • “I favor composition over inheritance unless there’s a true is-a relationship that respects Liskov substitution.”
  • “Overloading is resolved at compile time, while overriding uses dynamic dispatch at runtime.”
  • “The declared type decides what I can call; the runtime type decides what actually runs.”
  • “If I keep downcasting, it’s a sign the behavior belongs in the type itself, or in a sealed switch.”
  • “Constructors aren’t inherited; the subclass calls super(...) explicitly or relies on the implicit no-arg call.”
  • “Fields aren’t polymorphic: a field with the same name in the subclass only hides the parent’s.”
  • “When several overloads match, the compiler prefers widening over boxing, and boxing over varargs.”
  • “A square is a rectangle mathematically, but with setters it can’t honor the rectangle’s contract, so I’d model them as immutable siblings.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.