Skip to content
notes.vinhnq.com

Search

OOP & DesignMid18 min read

Object-oriented programming: abstract classes, interfaces and initialization order

Review 10 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

When code depends on “what can be done” rather than “who does it”, you can swap the implementation without touching the caller: that’s abstraction, the foundation of dependency injection and of mocking in tests. Afterwards you can choose between an abstract class and an interface, resolve default-method conflicts, and answer “what does this code print?” questions about initialization order. Read part 1 (classes, constructors, static) and part 3 (inheritance, polymorphism) first.

1. Abstraction

Key idea: abstraction keeps only the core behavior the caller needs and hides the implementation. Java has two tools: an abstract class for a family of classes that share code, and an interface for a capability that unrelated classes can have.

An abstract class can mix abstract methods (no body) with implemented ones, and can have fields and constructors. You can’t new it directly, and concrete subclasses must implement every abstract method. Its constructor still runs when a subclass is created, through the super(...) chain (constructor chaining: a child constructor calls the parent’s first).

public abstract class Employee {
    private final String id;
    protected Employee(String id) { this.id = id; }   // runs when a subclass is created

    public String id() { return id; }
    public abstract BigDecimal monthlySalary();       // subclasses must implement this

    public final String payslip() {                   // Template Method: a fixed skeleton
        return id + ": " + monthlySalary();
    }
}

payslip() above is a Template Method: the parent fixes the skeleton of the algorithm (final) and subclasses fill in the missing step. A few rules that come up in interviews:

  • A class with at least one abstract method must be declared abstract. The reverse isn’t required: an abstract class may have no abstract methods at all, just to forbid direct new.
  • An abstract method has no body (it ends with ;) and can’t be private, static or final, since all three would stop subclasses from overriding it.
  • A subclass that doesn’t implement every abstract method must itself be abstract.

An interface is a contract describing “what you can do”, and a class can implement many of them. Interfaces are the right tool for defining a common type across unrelated classes (Comparable, AutoCloseable, Runnable).

public interface Notifier {
    int MAX_RETRY = 3;                         // implicitly public static final
    void send(String to, String message);      // implicitly public abstract

    default void sendAll(List<String> to, String message) {   // Java 8+: a method with a body
        to.forEach(t -> send(t, message));
    }
    static Notifier noop() { return (to, msg) -> { }; }       // Java 8+: static method
}

On the backend, interfaces win by a wide margin. Code that depends on an interface (PaymentGateway) instead of a concrete class (StripeGateway) can swap implementations and mock them in tests. That is the foundation of Dependency Injection.

Java 17 added sealed interfaces and classes: only the classes listed in permits may implement them. So the compiler knows every case and checks that a switch handles them all (exhaustiveness):

public sealed interface PaymentResult permits Success, Failure { }
public record Success(String txId) implements PaymentResult { }
public record Failure(String reason) implements PaymentResult { }

String message = switch (result) {      // the compiler knows every case is handled; no default needed
    case Success s -> "OK " + s.txId();
    case Failure f -> "Failed: " + f.reason();
};

2. Initialization order

Key idea: static before instance, parent before child, initializers before the constructor body. The static part runs only once, when the class is first loaded.

The first time you run new Child(), Java goes through these steps:

  1. Load and initialize the classes (once per class): the parent class is initialized first, so Parent’s static { } blocks and static field initializers run, then Child’s, each in source order.
  2. Allocate the object: every field starts at its default value (0, false, null).
  3. Child’s constructor calls super(...) (explicitly or implicitly), so Parent’s part runs first: its field initializers and { } blocks in source order, then the body of Parent’s constructor.
  4. Back in Child: its field initializers and { } blocks, then the body of Child’s constructor.
class Parent {
    static { System.out.println("1. Parent static"); }
    { System.out.println("3. Parent instance init"); }
    Parent() { System.out.println("4. Parent constructor"); }
}
class Child extends Parent {
    static { System.out.println("2. Child static"); }
    { System.out.println("5. Child instance init"); }
    Child() { System.out.println("6. Child constructor"); }
}

new Child();   // prints 1 → 6
new Child();   // the second time prints only 3 → 6: the static part already ran

Think of building a housing estate: the shared foundation (static) is poured once, then each house gets its lower floor (parent) before its upper floor (child).

Exercises

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

1. A hotel management system (only in the second copy of the slides)

Requirements: entities such as receptionists, housekeepers, managers, the hotel and its rooms; at least one abstract class, at least two interfaces, and at least one overridden and one overloaded method. Features: configure rooms, configure staff, assign rooms to a staff member, list the rooms a staff member looks after, and compute salary from the number of assigned rooms and a weight.

classDiagram
  class Payable {
    <<interface>>
    +monthlySalary() BigDecimal
  }
  class RoomAssignable {
    <<interface>>
    +assign(Room room)
    +rooms() List~Room~
  }
  class Employee {
    <<abstract>>
    -String id
    -String name
    #BigDecimal baseSalary
    +monthlySalary()* BigDecimal
  }
  class Housekeeper
  class Receptionist
  class Manager
  class Hotel {
    -Map rooms
    -Map staff
    +addRoom(Room)
    +hire(Employee)
    +assign(String employeeId, String roomNumber)
  }
  class Room {
    <<record>>
    +String number
    +RoomType type
  }
  Payable <|.. Employee
  RoomAssignable <|.. Housekeeper
  Employee <|-- Housekeeper
  Employee <|-- Receptionist
  Employee <|-- Manager
  Hotel o-- Employee
  Hotel *-- Room
Solution to exercise 1: full Java code and a salary example
interface Payable { BigDecimal monthlySalary(); }

interface RoomAssignable {
    void assign(Room room);
    List<Room> rooms();
}

enum RoomType {
    STANDARD(1.0), DELUXE(1.5), SUITE(2.0);          // workload weight per room type
    final double weight;
    RoomType(double weight) { this.weight = weight; }
}

record Room(String number, RoomType type) { }

abstract class Employee implements Payable {
    private final String id;
    private final String name;
    protected final BigDecimal baseSalary;

    protected Employee(String id, String name, BigDecimal baseSalary) {
        this.id = id; this.name = name; this.baseSalary = baseSalary;
    }
    public String id() { return id; }
    public String name() { return name; }
    @Override public String toString() { return getClass().getSimpleName() + "(" + id + ", " + name + ")"; }
}

class Housekeeper extends Employee implements RoomAssignable {
    private static final BigDecimal PER_WEIGHT = new BigDecimal("500000");
    private final List<Room> rooms = new ArrayList<>();

    Housekeeper(String id, String name, BigDecimal base) { super(id, name, base); }

    @Override public void assign(Room room) { rooms.add(room); }
    public void assign(Room... many) { for (Room r : many) assign(r); }     // overload
    @Override public List<Room> rooms() { return List.copyOf(rooms); }      // don't expose the internal list

    @Override public BigDecimal monthlySalary() {                           // override
        double totalWeight = rooms.stream().mapToDouble(r -> r.type().weight).sum();
        return baseSalary.add(PER_WEIGHT.multiply(BigDecimal.valueOf(totalWeight)))
                         .setScale(0, RoundingMode.HALF_UP);
    }
}

class Receptionist extends Employee {
    Receptionist(String id, String name, BigDecimal base) { super(id, name, base); }
    @Override public BigDecimal monthlySalary() { return baseSalary; }
}

class Manager extends Employee {
    Manager(String id, String name, BigDecimal base) { super(id, name, base); }
    @Override public BigDecimal monthlySalary() { return baseSalary.multiply(new BigDecimal("1.5")); }
}

class Hotel {
    private final Map<String, Room> rooms = new LinkedHashMap<>();
    private final Map<String, Employee> staff = new LinkedHashMap<>();

    void addRoom(Room room) { rooms.put(room.number(), room); }           // configure rooms
    void hire(Employee e) { staff.put(e.id(), e); }                       // configure staff

    void assign(String employeeId, String roomNumber) {                   // assign a room to someone
        Room room = Optional.ofNullable(rooms.get(roomNumber))
                .orElseThrow(() -> new NoSuchElementException("No room " + roomNumber));
        if (!(staff.get(employeeId) instanceof RoomAssignable worker))
            throw new IllegalArgumentException(employeeId + " can't be assigned rooms");
        worker.assign(room);
    }

    List<Room> roomsOf(String employeeId) {                               // rooms one person looks after
        return staff.get(employeeId) instanceof RoomAssignable w ? w.rooms() : List.of();
    }

    BigDecimal payroll() {                                                // polymorphism: no type checks needed
        return staff.values().stream().map(Payable::monthlySalary).reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

Example: a housekeeper with a base salary of 6,000,000 who looks after one STANDARD room (weight 1) and one SUITE (weight 2) earns 6,000,000 + 500,000 × 3 = 7,500,000.

Design points worth raising in an interview:

  • Hotel.payroll() has no if on the employee type at all, thanks to polymorphism. A new employee type means just a new class.
  • Only employees implementing RoomAssignable can be assigned rooms, so Receptionist isn’t forced to carry a meaningless assign method. That is the Interface Segregation Principle (don’t make a class depend on methods it doesn’t use).
  • Money uses BigDecimal. In a real system, the salary rules would move into a separate SalaryPolicy, so they can change without touching the employee classes.

2. Lab 06: an abstract Person class and a Trainable interface

Task (paraphrased): an abstract Person class has a name, an age, a constructor, getters/setters, a method that introduces the person (“My name is …, I am … years old.”) and an abstract work() method. A Trainable interface has a method for attending training on a topic and a default method that thanks everyone after the session. Two subclasses, an engineer (with a specialty) and a manager (with a team size), both implement Trainable and print their own work and training lines. In main, build a Person[] holding both kinds, loop over it calling the introduction and work(), and if an element is Trainable, cast it and call the training method and the thank-you.

Solution to Lab 06: code, output and what to notice
import java.util.List;
import java.util.Objects;

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

        protected Person(String name, int age) {               // an abstract class still has a constructor
            this.name = Objects.requireNonNull(name, "name");
            if (age < 0) throw new IllegalArgumentException("age must be >= 0");
            this.age = age;
        }

        public String getName() { return name; }
        public int getAge() { return age; }

        public void introduce() {
            System.out.printf("My name is %s, I am %d years old.%n", name, age);
        }

        public abstract void work();                           // every concrete subclass must implement it
    }

    interface Trainable {
        void attendTraining(String topic);

        default void feedback() {                              // Java 8+: a method with a body inside an interface
            System.out.println("Thanks for the training session.");
        }
    }

    static final class Engineer extends Person implements Trainable {
        private final String specialty;

        Engineer(String name, int age, String specialty) {
            super(name, age);
            this.specialty = specialty;
        }

        @Override public void work() {
            System.out.printf("Engineer %s is working on %s project.%n", getName(), specialty);
        }

        @Override public void attendTraining(String topic) {
            System.out.printf("Engineer %s is attending training on %s.%n", getName(), topic);
        }
    }

    static final class Manager extends Person implements Trainable {
        private final int teamSize;

        Manager(String name, int age, int teamSize) {
            super(name, age);
            this.teamSize = teamSize;
        }

        @Override public void work() {
            System.out.printf("Manager %s is managing a team of %d people.%n", getName(), teamSize);
        }

        @Override public void attendTraining(String topic) {
            System.out.printf("Manager %s is attending management training on %s.%n", getName(), topic);
        }
    }

    static final class Intern extends Person {                 // not Trainable: shows the instanceof-false branch
        Intern(String name, int age) { super(name, age); }
        @Override public void work() { System.out.println("Intern " + getName() + " is shadowing the team."); }
    }

    public static void main(String[] args) {
        Person[] people = {                                    // upcast: a parent-typed array holding subclass objects
            new Engineer("Lan", 25, "AI"),
            new Manager("Minh", 40, 10),
            new Intern("Hoa", 20)
        };
        String[] topics = {"Cloud Computing", "Leadership", "Git"};

        for (int i = 0; i < people.length; i++) {
            Person p = people[i];
            p.introduce();                                     // shared method from the parent
            p.work();                                          // dynamic dispatch on the runtime type
            if (p instanceof Trainable t) {                    // test and cast in one step (Java 16+)
                t.attendTraining(topics[i]);
                t.feedback();
            }
        }
    }
}
My name is Lan, I am 25 years old.
Engineer Lan is working on AI project.
Engineer Lan is attending training on Cloud Computing.
Thanks for the training session.
My name is Minh, I am 40 years old.
Manager Minh is managing a team of 10 people.
Manager Minh is attending management training on Leadership.
Thanks for the training session.
My name is Hoa, I am 20 years old.
Intern Hoa is shadowing the team.

What to notice:

  • Person is abstract because there’s no “generic person” to new. Its protected constructor still runs through each subclass’s super(...).
  • The abstract work() forces every concrete subclass to implement it; introduce() is shared code in the parent.
  • Trainable is a capability unrelated to the class hierarchy: the Intern I added to show the false branch is a Person but not Trainable. feedback() is a default method, so every implementing class gets it for free.
  • In the loop, introduce()/work() are dynamic dispatch; p instanceof Trainable t (Java 16) combines the check and the cast, replacing if (p instanceof Trainable) { Trainable t = (Trainable) p; ... }.

What a senior reviewer would say about this solution:

  • The instanceof-then-downcast (casting down to a subtype) is what the task asks for, to practice the syntax. Real code should take a List<Trainable> directly, or filter once at the boundary: people.stream().filter(Trainable.class::isInstance).map(Trainable.class::cast). Scattered downcasts signal missing polymorphism (see part 3).
  • Pairing topics with people through the index of a parallel array (topics[i]) breaks easily; put them together in a record TrainingPlan(Person person, String topic).
  • Default methods are exactly the tool for evolving a published interface without breaking existing implementations; Java 8 added them so Collection could gain stream() without breaking every implementation out there.

Remember

  • Explain when to pick an abstract class versus an interface, and why the backend uses interfaces more.
  • Know which kinds of methods interfaces gained in Java 8/9, and what interfaces still can’t have.
  • Resolve two interfaces bringing the same default method, and state the “class wins” rule.
  • Write out what static blocks, instance blocks and constructors print when you call new Child() twice.
  • Explain why you shouldn’t call an overridable method from a constructor, and what to do instead.

Interview questions

Junior

Can an abstract class have a constructor? Must it have an abstract method?

Yes, it can have constructors, and no, it doesn’t need an abstract method.

You can’t call the constructors with new directly, but they run through super(...) when a subclass object is created, to initialize and validate the shared state. An abstract class may have no abstract methods and exist just to forbid direct instantiation. Conversely, a class with an abstract method must be abstract, and so must a subclass that doesn’t implement all of them.

Mid

Abstract class versus interface: what’s the difference, and when do you use each?

An abstract class has state and constructors and supports single inheritance. An interface has no instance state, and a class can implement many.

Since Java 8 interfaces also have default/static methods. Use an abstract class when subclasses of one family share code and state (e.g. the Template Method pattern). Use an interface to define a contract or capability, and as the seam for dependency injection.

On the first new Child(), in what order do static blocks, instance blocks and constructors run?

Static before instance, parent before child, initializers before the constructor body.

In detail: Parent’s statics, Child’s statics (only when the class is first initialized), then Parent’s field initializers and { } blocks, Parent’s constructor, Child’s field initializers and { } blocks, and finally Child’s constructor. A second new skips the static part.

What happens when a class implements two interfaces with the same default method?

If neither interface is more specific, the compiler reports an error and forces the class to override; inside the override you can call A.super.hello() or B.super.hello().

If the class’s superclass already has that method, the class method wins and nothing is needed (“class wins”). If one interface extends the other, the more specific interface wins. That’s how Java allows multiple inheritance of behavior through interfaces while still avoiding the diamond problem for state.

Senior

How do sealed interfaces (Java 17) help with domain modeling?

They restrict the set of implementations, so you can model “one of these cases” (a sum type) and the compiler checks that a switch covers every case.

For example PaymentResult = Success | Failure. Combined with records and pattern-matching switch, the compiler checks exhaustiveness. Add a new case and every switch that doesn’t handle it fails to compile, instead of silently falling into default at runtime.

Why is calling an overridable method from a constructor dangerous?

The parent’s constructor runs before the subclass fields are initialized, yet dynamic dispatch still calls the subclass override.

That override reads fields that are still null/0, which leads to a NullPointerException or subtly wrong state that is hard to track down. To avoid it, call only private/static/final methods from constructors, use a factory method for subclass-specific setup, and don’t let this escape (listeners, threads) before construction finishes.

Useful phrases for interviews

  • “I code against interfaces, so the implementation can be swapped or mocked in tests.”
  • “With a sealed hierarchy, the compiler forces every switch to handle all cases.”
  • “I never call an overridable method from a constructor, because the subclass fields aren’t initialized yet.”
  • “I use an abstract class when subclasses share state and code, and an interface for a capability that unrelated classes can have.”
  • “A default method lets you evolve a published interface without breaking existing implementations.”
  • “Static before instance, parent before child, initializers before the constructor body: that’s the initialization order.”
  • “An abstract class may have no abstract methods at all; sometimes it only exists to forbid direct instantiation.”
  • “When two interfaces bring the same default method, the class must override it and can delegate with A.super.method().”

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.