Tutorials / Java: From Zero to Advanced / Inheritance, abstract classes and interfaces

Inheritance, abstract classes and interfaces

15 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Is-a relationships

Inheritance lets a class take on the fields and methods of another. A Dog is an Animal, so Dog can extend Animal and add or change behaviour. Java allows a class to extend exactly one class, but to implement many interfaces.

Interfaces: a contract

An interface lists methods that a class promises to provide. It says what, not how. Code that depends on the interface works with any class that implements it. This is the main tool for making code flexible, and I use it far more than inheritance.

import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<Notifier> notifiers = List.of(
                new EmailNotifier("noreply@example.com"),
                new SmsNotifier(),
                new ConsoleNotifier());

        for (Notifier n : notifiers) {
            n.send("sara@example.com", "Your order has shipped.");   // polymorphism
        }
        notifiers.get(0).sendAll(List.of("a@example.com", "b@example.com"), "Maintenance tonight");

        System.out.println();

        List<Employee> staff = List.of(
                new Manager("Hina", 9000, 3),
                new Developer("Omar", 7000, "Java"),
                new Developer("Zara", 7500, "Kotlin"));

        double total = 0;
        for (Employee e : staff) {
            System.out.println(e.describe());
            total += e.monthlyPay();
        }
        System.out.println("Payroll: " + total);

        // Pattern matching for instanceof (Java 16+)
        for (Employee e : staff) {
            if (e instanceof Developer d) {
                System.out.println(d.name() + " writes " + d.language());
            }
        }
    }

    interface Notifier {
        void send(String to, String message);

        // A default method gives implementers behaviour for free
        default void sendAll(List<String> recipients, String message) {
            for (String r : recipients) {
                send(r, message);
            }
        }
    }

    static class EmailNotifier implements Notifier {
        private final String from;

        EmailNotifier(String from) { this.from = from; }

        @Override
        public void send(String to, String message) {
            System.out.println("EMAIL from " + from + " to " + to + ": " + message);
        }
    }

    static class SmsNotifier implements Notifier {
        @Override
        public void send(String to, String message) {
            System.out.println("SMS to " + to + ": " + message);
        }
    }

    static class ConsoleNotifier implements Notifier {
        @Override
        public void send(String to, String message) {
            System.out.println("[console] " + to + " - " + message);
        }
    }

    static abstract class Employee {
        private final String name;
        protected final double baseSalary;

        protected Employee(String name, double baseSalary) {
            this.name = name;
            this.baseSalary = baseSalary;
        }

        String name() { return name; }

        // Subclasses must supply this
        abstract double monthlyPay();

        // Shared code that uses the abstract method
        String describe() {
            return getClass().getSimpleName() + " " + name + " earns " + monthlyPay();
        }
    }

    static class Manager extends Employee {
        private final int teamSize;

        Manager(String name, double baseSalary, int teamSize) {
            super(name, baseSalary);          // must be the first statement
            this.teamSize = teamSize;
        }

        @Override
        double monthlyPay() {
            return baseSalary + teamSize * 200;
        }
    }

    static class Developer extends Employee {
        private final String language;

        Developer(String name, double baseSalary, String language) {
            super(name, baseSalary);
            this.language = language;
        }

        String language() { return language; }

        @Override
        double monthlyPay() {
            return baseSalary;
        }

        @Override
        String describe() {
            return super.describe() + " (" + language + ")";
        }
    }
}

Walking through it

The Notifier interface has one required method and one default method. Three classes implement it. The loop in main holds them all in a List<Notifier> and calls send. Each object runs its own version. This is polymorphism: the variable's type decides which methods you can call, and the object's real class decides which code runs. To add a Telegram notifier, you write one more class. The loop does not change. This is how large systems stay open to new features.

The @Override annotation is not required, but always use it. It asks the compiler to check that you really override something. If you misspell the method name or get a parameter type wrong, you get a compile error instead of a silent new method.

Employee is an abstract class. It cannot be instantiated with new. It holds shared fields and code, and declares monthlyPay as abstract, so every subclass must define it. The method describe in the base class calls monthlyPay, and Java runs the version of the actual object. This arrangement is known as the template method pattern.

A subclass constructor must call a superclass constructor with super(...), and that call must come first. If you do not write one, Java calls the no-argument constructor of the parent, and that fails to compile when the parent has none. Developer overrides describe and calls super.describe() to extend the parent's behaviour rather than replace it.

The access level protected means the member is visible to subclasses and to other classes in the same package. The checks in instanceof Developer d let you use the object as a Developer inside the if without a manual cast.

Interface or abstract class

  • Use an interface for a capability that unrelated classes can share, or when you expect many implementations. A class can implement several.
  • Use an abstract class when related classes share real state and code, and you want to force them to fill in some steps.

Prefer composition

Deep inheritance trees become fragile. A change in the base class can break any subclass. When you only want to reuse behaviour, and the relationship is "has a" rather than "is a", hold another object in a field and call its methods. A Car has an Engine. It is not an engine. I follow a simple rule: inheritance for a stable, shallow "is a" relationship, composition for the rest.

Common mistakes

  • Inheriting just to reuse a method. That creates a false "is a" relationship.
  • Forgetting @Override.
  • Calling an overridable method from a constructor. The subclass may not be initialised yet.
  • Overloading when you meant to override. The parameter types differ slightly, so the base version still runs.
  • Casting without checking. A wrong cast throws ClassCastException. Use instanceof first.

Try it yourself

  1. Create an interface Discount with double apply(double price). Implement PercentDiscount and FixedDiscount.
  2. Write an abstract class Shape with an abstract area() and add Circle and Rectangle.
  3. Put the shapes in a list and print the one with the largest area.
java
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<Notifier> notifiers = List.of(
                new EmailNotifier("noreply@example.com"),
                new SmsNotifier(),
                new ConsoleNotifier());

        for (Notifier n : notifiers) {
            n.send("sara@example.com", "Your order has shipped.");   // polymorphism
        }
        notifiers.get(0).sendAll(List.of("a@example.com", "b@example.com"), "Maintenance tonight");

        System.out.println();

        List<Employee> staff = List.of(
                new Manager("Hina", 9000, 3),
                new Developer("Omar", 7000, "Java"),
                new Developer("Zara", 7500, "Kotlin"));

        double total = 0;
        for (Employee e : staff) {
            System.out.println(e.describe());
            total += e.monthlyPay();
        }
        System.out.println("Payroll: " + total);

        // Pattern matching for instanceof (Java 16+)
        for (Employee e : staff) {
            if (e instanceof Developer d) {
                System.out.println(d.name() + " writes " + d.language());
            }
        }
    }

    interface Notifier {
        void send(String to, String message);

        // A default method gives implementers behaviour for free
        default void sendAll(List<String> recipients, String message) {
            for (String r : recipients) {
                send(r, message);
            }
        }
    }

    static class EmailNotifier implements Notifier {
        private final String from;

        EmailNotifier(String from) { this.from = from; }

        @Override
        public void send(String to, String message) {
            System.out.println("EMAIL from " + from + " to " + to + ": " + message);
        }
    }

    static class SmsNotifier implements Notifier {
        @Override
        public void send(String to, String message) {
            System.out.println("SMS to " + to + ": " + message);
        }
    }

    static class ConsoleNotifier implements Notifier {
        @Override
        public void send(String to, String message) {
            System.out.println("[console] " + to + " - " + message);
        }
    }

    static abstract class Employee {
        private final String name;
        protected final double baseSalary;

        protected Employee(String name, double baseSalary) {
            this.name = name;
            this.baseSalary = baseSalary;
        }

        String name() { return name; }

        // Subclasses must supply this
        abstract double monthlyPay();

        // Shared code that uses the abstract method
        String describe() {
            return getClass().getSimpleName() + " " + name + " earns " + monthlyPay();
        }
    }

    static class Manager extends Employee {
        private final int teamSize;

        Manager(String name, double baseSalary, int teamSize) {
            super(name, baseSalary);          // must be the first statement
            this.teamSize = teamSize;
        }

        @Override
        double monthlyPay() {
            return baseSalary + teamSize * 200;
        }
    }

    static class Developer extends Employee {
        private final String language;

        Developer(String name, double baseSalary, String language) {
            super(name, baseSalary);
            this.language = language;
        }

        String language() { return language; }

        @Override
        double monthlyPay() {
            return baseSalary;
        }

        @Override
        String describe() {
            return super.describe() + " (" + language + ")";
        }
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account