• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Classes need a way to define behavioral contracts without dictating implementation. Without interfaces, achieving polymorphism across unrelated class hierarchies would require a common abstract superclass — forcing artificial inheritance relationships and preventing multiple type identities.

Core Idea

An interface in Java is a reference type that defines a set of abstract method signatures (a contract) that implementing classes must fulfill. Unlike classes, interfaces support multiple inheritance — a class can implement multiple interfaces. Java 8+ added default methods (with body) and static methods in interfaces.

How It Works

When a class declares implements InterfaceName, the compiler checks that the class provides implementations for all abstract interface methods. At runtime, interface method dispatch uses the itable (interface method table), which is resolved differently from the vtable. A class can implement multiple interfaces, each defining a distinct role.

Visual Explanation

java_interfaces Flyable interface Flyable void fly() Swimmable interface Swimmable void swim() Duck class Duck implements Flyable, Swimmable fly() { ... } swim() { ... } Duck->Flyable implements Duck->Swimmable implements

Semantic Network

semantic_interfaces THIS Interfaces POLY Polymorphism THIS--POLY builds into ABS Abstraction THIS--ABS related LAMB Lambda Expressions THIS--LAMB builds into INHER Inheritance THIS--INHER contrasts with

Key Properties

  • Multiple inheritance: A class can implement many interfaces
  • All methods are public: Interface methods are implicitly public abstract
  • Default methods (Java 8+): Methods with a body in interfaces, enabling backward-compatible evolution
  • Functional interfaces: Interfaces with exactly one abstract method — target for lambda expressions

Connections

Edge Cases & Gotchas

  • Default method diamond problem: If two interfaces define the same default method, the class must override
  • Interface constants: Fields in interfaces are implicitly public static final
  • FunctionalInterface annotation: @FunctionalInterface is a documentation aid — the compiler validates single abstract method
  • Sealed interfaces (Java 17+): Restrict which classes can implement an interface