beginnerFree

Interfaces

Contract - what a class must do, not how

Interfaces

Interfaces define behavior contracts. A class can implement multiple interfaces.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:23

The Big Picture

Interfaces define contracts - method signatures that classes must implement. They enable polymorphism without inheritance.

  • Classes can implement multiple interfaces
  • Essential: List, Comparable, Runnable
  • Allow unrelated classes to share behavior

Central to "program to an interface" design principle.

How It Works

Abstract interface methods have no body; default, static, and private methods can have bodies. JVM uses itables to dispatch.

  • Abstract methods implicitly public abstract
  • Fields are public static final constants
  • Java 8+ allows default and static methods
  • Java 9+ allows private helper methods

In the Java Landscape

Interfaces are central to Java's design philosophy.

  • Collections, streams, concurrency APIs use them heavily
  • Functional interfaces enable lambdas (Java 8+)
  • Marker interfaces (Serializable) tag classes
  • Sealed interfaces (Java 17+) restrict implementations
  • default methods blur the line with abstract classes

Pitfalls and Best Practices

  • Keep interfaces small and focused (ISP)
  • Program to interfaces, not implementations
  • Use default methods to evolve APIs without breaking clients
  • Don't use interfaces as constant holders
  • Prefer single-method interfaces for functional use
#java#oop#interfaces