Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

implements

Lists the interfaces that a class implements.

Available since: Java 1.0

Syntax

class Name implements Interface1, Interface2 { … }

Examples

A class implements Comparable and becomes sortable:

class Task implements Comparable<Task> {
    String title;
    int priority;
 
    Task(String title, int priority) {
        this.title = title;
        this.priority = priority;
    }
 
    @Override
    public int compareTo(Task other) {
        return Integer.compare(priority, other.priority);
    }
 
    @Override
    public String toString() {
        return title;
    }
}
 
void main() {
    var tasks = new ArrayList<>(List.of(new Task("deploy", 3), new Task("test", 1)));
    Collections.sort(tasks);
    IO.println(tasks);
}

Output:

[test, deploy]

Notes

If the class misses a method of the interface, the compiler reports "Task is not abstract and does not override abstract method compareTo(Task) in Comparable". With inheritance, extends comes first, then implements.

See also

  • interface — Declares an interface — a set of methods that a class promises to implement.
  • extends — Declares inheritance: the class gets the parent's fields and methods.
  • Comparable.compareTo() — Defines the natural order of a class — used by sort() and TreeSet.

In the tutorial

  • Interfaces — Interfaces in Java: implements, several interfaces in one class, an interface as a type and default methods.

Thanks for reading!

Donate to the site — we work hard for you.