Interface (Java)

An interface is a contract that lists methods a class must provide, without saying how they work. A class that 'implements' an interface promises to supply a body for each of those methods.

Java

Interfaces define what a class can do, separate from how it does it. Unlike a class, a Java class can implement many interfaces, which is how Java achieves flexibility without multiple class inheritance.

You declare one with the interface keyword and connect a class to it with implements.

Examples

Java

interface Shape {
    double area();
}

class Square implements Shape {
    double side = 4;
    public double area() { return side * side; }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Square();
        System.out.println(s.area());
    }
}

Output:

16.0

Learn it in a lesson

See also

Back to the Dictionary