Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

interface

Declares an interface — a set of methods that a class promises to implement.

Available since: Java 1.0

Syntax

interface Name { Type method(); default Type other() { … } }

Examples

An interface and two implementations:

interface Shape {
    double area();
}
 
class Circle implements Shape {
    double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}
 
class Square implements Shape {
    double side;
    Square(double side) { this.side = side; }
    public double area() { return side * side; }
}
 
void main() {
    List<Shape> shapes = List.of(new Circle(1), new Square(2));
    for (Shape s : shapes) {
        IO.println(Math.round(s.area() * 100) / 100.0);
    }
}

Output:

3.14
4.0

A default method with a ready implementation, and a static method:

interface Greeter {
    String name();
 
    default String greet() {
        return "Hello, " + name() + "!";
    }
 
    static Greeter of(String name) {
        return () -> name;
    }
}
 
void main() {
    IO.println(Greeter.of("Anna").greet());
}

Output:

Hello, Anna!

Notes

Interface methods are public and abstract by default, so the implementing class declares them public. A class can implement many interfaces but extend only one class. An interface with a single abstract method is functional: it can be implemented with a lambda, as Greeter.of() does above.

See also

  • implements — Lists the interfaces that a class implements.
  • abstract — Marks a class that cannot be instantiated and a method without a body that subclasses implement.
  • sealed / permits — Restricts which classes may extend a class or implement an interface.

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.