Java ยท Chapter 29 of 42

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.

Syntax
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.

Example 1 (java)
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();
  }
}
Output
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.
๐Ÿ’ก Note: Favor programming to interfaces rather than concrete classes for more flexible, testable code.

๐Ÿ“ Quick Quiz

1. Which keyword lets a class use an interface?

2. Can a class implement multiple interfaces?

3. What Java version introduced default methods on interfaces?