Skip to content

Interfaces — advanced (course memo)

Java. Interfaces have changed a lot since Java 8 — originally they were never supposed to contain any code, but that release (alongside Streams) added new features to them.

Complete list of interface features

  • Constant variables
  • Abstract methods
  • Default methods
  • Static methods
  • Private methods
  • Private static methods

Best practice: still mostly use interfaces just for abstract methods (defining what a group of implementations must provide) — the other features exist for specific cases.

When the other features are useful

Constant variables

  • A value that never changes and is used across many places in a project.
  • A library/set of classes sharing common configuration values — changing the constant changes behavior everywhere without touching the classes themselves.

Default methods

  • An interface method that almost always has the same implementation, except in a few cases — those particular cases get their own class overriding the default.
  • A diverse set of implementations where, absent a specific override, falling back to a shared default behavior makes sense.

Static methods

  • Utility-style methods that never depend on instance state (attributes) — an interface can hold these instead of a separate utility class.
  • Cannot be used for public static void main.

Private methods

  • When the code inside default/static interface methods gets duplicated or too long, private methods let you factor out shared logic within the interface itself, for cleanliness — same motivation as private helper methods in a regular class.