Default interface methods
Add method implementations directly in interfaces, enabling multiple inheritance of behavior.
Porównanie kodu
✕ Java 7
// Need abstract class to share behavior
public abstract class AbstractLogger {
public void log(String msg) {
System.out.println(
timestamp() + ": " + msg);
}
abstract String timestamp();
}
// Single inheritance only
public class FileLogger
extends AbstractLogger { ... }
✓ Java 8+
public interface Logger {
default void log(String msg) {
IO.println(
timestamp() + ": " + msg);
}
String timestamp();
}
// Multiple interfaces allowed
public class FileLogger
implements Logger, Closeable { ... }
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Multiple inheritance
Classes can implement many interfaces with default methods, unlike single abstract class inheritance.
API evolution
Add new methods to interfaces without breaking existing implementations.
Composable behavior
Mix and match capabilities from multiple interfaces freely.
Stare podejście
Abstract classes for shared behavior
Nowoczesne podejście
Default methods on interfaces
Od JDK
8
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Default interface methods
Dostępne
Available since JDK 8 (March 2014).
Jak to działa
Before Java 8, sharing behavior across unrelated classes required abstract classes, which limited you to single inheritance. Default methods let interfaces provide method implementations, so classes can inherit behavior from multiple interfaces. This was essential for evolving the Collections API (e.g., List.forEach, Map.getOrDefault) without breaking existing implementations.
Powiązana dokumentacja