Learn / Programming / Java / Interfaces and Abstract Classes

Java · Lesson 11 of 15

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 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

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.
Up next · Lesson 12GenericsType-safe containers and methods with type parameters and bounds.