Skip to content
Codewilds

Lesson 27 of 34 · Inheritance & Interfaces

Java Interfaces: implements, default Methods and Comparable

medium20 XP3 min read

Abstract classes share code along one family tree. But some abilities cut right across unrelated classes: a bird and a plane can both fly, a player and a coin can both be compared. Java describes such abilities with interfaces — contracts that any class can promise to fulfil.

Declaring and implementing an interface

interface Greeter {
    String greet(String name);   // implicitly public and abstract
}

class FriendlyGreeter implements Greeter {
    @Override
    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

class PirateGreeter implements Greeter {
    @Override
    public String greet(String name) {
        return "Ahoy, " + name + "!";
    }
}

An interface lists method signatures without bodies. A class that implements it must provide every one of them — otherwise it does not compile. Interface methods are automatically public, so the implementing methods must be public as well.

Interfaces are types

Just like a superclass, an interface can be the type of a variable, parameter, array or list. Code written against the interface works with every implementation:

Greeter[] greeters = { new FriendlyGreeter(), new PirateGreeter() };
for (Greeter g : greeters) {
    System.out.println(g.greet("Ada"));
}
Hello, Ada!
Ahoy, Ada!

A class extends at most one class but may implement many interfaces: class Duck extends Bird implements Flyer, Swimmer { ... }. That is how one object can play several roles.

default methods, static methods and constants

Since Java 8, an interface can also contain code:

interface Greeter {
    String greet(String name);

    default String greetTwice(String name) {   // inherited by every implementation
        return greet(name) + " " + greet(name);
    }

    static Greeter pirate() {                   // called as Greeter.pirate()
        return new PirateGreeter();
    }

    int MAX_NAME_LENGTH = 20;                   // a constant: public static final
}

A default method is built on top of the abstract ones, like a template method, and implementations may override it. Interfaces cannot have instance fields or constructors — that is the main difference from abstract classes. Rule of thumb: use an abstract class for a family that shares state, an interface for a capability.

Comparable: an interface from the JDK

Comparable<T> has a single method, int compareTo(T other). It returns a negative number if this comes before other, zero if they rank equally and a positive number if this comes after. Implement it, and Collections.sort can sort your objects:

class Coin implements Comparable<Coin> {
    final String name;
    final int value;

    Coin(String name, int value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public int compareTo(Coin other) {
        return Integer.compare(value, other.value);  // smallest value first
    }
}

List<Coin> purse = new ArrayList<>(List.of(
        new Coin("gold", 100), new Coin("copper", 1), new Coin("silver", 10)));
Collections.sort(purse);  // copper, silver, gold

Swap the arguments — Integer.compare(other.value, value) — to sort from largest to smallest. Strings are already Comparable: "apple".compareTo("banana") is negative.

Common mistakes

  • Missing public on an implementing method: attempting to assign weaker access privileges; was public.
  • Forgetting a method: X is not abstract and does not override abstract method ....
  • new Greeter(): an interface cannot be instantiated — create an object of an implementing class.
  • Subtraction in compareTo: return value - other.value; overflows for large numbers. Integer.compare is always safe.

Assignment

Part 1 — the leaderboard. Player stores a name and a score.

  1. Make Player implement Comparable<Player>: the higher score comes first; players with equal scores are ordered by name A→Z.
  2. Main.ranking(List<Player> players) returns a new list with the players in that order; the list passed in must stay unchanged.

Part 2 — word scoring. The interface Scorer has int score(String word).

  1. Implement the default method beats(String a, String b): true when a scores strictly higher than b.
  2. LengthScorer scores a word by its number of characters; VowelScorer by its number of vowels (a e i o u, upper or lower case).
  3. Main.bestWord(List<String> words, Scorer scorer) returns the word with the highest score (the first one on a tie), or "" for an empty list.
new VowelScorer().score("Highlands")                                       // 2
bestWord(List.of("java", "bytecode", "queue", "sky"), new LengthScorer())  // "bytecode"

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Interfaces in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 27 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.