Java · Lesson 11 of 20

Interfaces and Abstract Classes

Contracts, default methods and when to choose an interface or an abstract class.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 10: Inheritance and Polymorphism

What you will learn

  • Define an interface
  • Write an abstract class
  • Choose between them

Your Progress

0 of 20 lessons 0%

  • Lessons0 / 20
  • Completed0
  • Est. time left~ 5 hours

Progress is saved in this browser. No account needed.

Tip: pressing Next marks this lesson complete automatically.

Both interfaces and abstract classes describe what a type can do without fixing every detail. They solve slightly different problems.

Interfaces: a contract

interface Payable {
    double amount();
    default String receipt() {          // optional shared behaviour
        return "Pay " + amount();
    }
}

class Invoice implements Payable {
    public double amount() { return 250.0; }
}

public class Main {
    public static void main(String[] args) {
        Payable p = new Invoice();
        System.out.println(p.receipt());
    }
}
Output
Pay 250.0

A class may implement many interfaces. Interface methods are public by default and interfaces hold no instance state.

Abstract classes: a partial implementation

abstract class Report {
    void print() {                     // template shared by all reports
        System.out.println("== " + title() + " ==");
        System.out.println(body());
    }
    abstract String title();
    abstract String body();
}

class Sales extends Report {
    String title() { return "Sales"; }
    String body() { return "Up 12%"; }
}

public class Main {
    public static void main(String[] args) {
        new Sales().print();
    }
}
Output
== Sales ==
Up 12%

You cannot create an instance of an abstract class. It can have fields, constructors and concrete methods.

Which one?

  • Use an interface to say what something can do (Comparable, Runnable), especially across unrelated classes.
  • Use an abstract class when related classes share state or code and you want to force subclasses to fill the gaps.
  • When unsure, start with an interface; it is more flexible.

Finished reading? Mark this lesson complete to track your progress.

Up next · Lesson 12Enums, Records and OptionalModel data cleanly in Java with enums (fields, methods, EnumMap), immutable records with compact constructors, and Optional for missing values.