Java Interfaces
An interface defines a contract of methods that implementing classes must provide, using the `implements` keyword. Unlike abstract classes, a class can implement multiple interfaces, enabling a form of multiple inheritance.
Since Java 8, interfaces can also have default methods (with a body) and static methods, in addition to abstract method signatures.
interface I {
void method();
}
class C implements I {
public void method() { }
}Defining and implementing
An interface declares method signatures without bodies (unless default/static). A class uses `implements` to promise it provides those methods.
Default and static methods
default methods provide a body that implementing classes inherit unless they choose to override it, useful for evolving interfaces without breaking existing code.
interface Vehicle {
void start();
default void stop() { System.out.println("Stopping..."); }
}
class Car implements Vehicle {
public void start() { System.out.println("Car starting"); }
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
v.stop();
}
}Car starting
Stopping...Car implements start(), and inherits the default stop() implementation from Vehicle.
Key points
- Interfaces define a contract of methods.
- A class can implement multiple interfaces.
- default methods provide a body directly in the interface.
- Interface methods are implicitly public.
