Java Clean Design: Default Methods
Lets’s Say we have an interface:
Vehicle has a start Absract Method
interface Vehicle {
void start();
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starting...");
}
}
What If I change My Interface?
interface Vehicle {
void start();
void throttle();
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starting...");
}
@Override
public void throttle() {
System.out.println("Car throttling...");
}
}
So If I change my interface all implementations would have to change
What If I provide a default Method of throttle in The Vehicle Interface and all Implementations would work fine then.
interface Vehicle {
void start();
default void throttle() {
System.out.println("throttling vehicle...");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starting...");
}
}
Now Let’s See in Theory
Traditionally, a Java interface groups related methods together into a contract.
Any (non abstract) class that implements an interface must provide an implementation for each method defined by the interface or inherit the implementation from a superclass.
But this requirement causes a problem when library designers need to update an interface to add a new method.
The Problem as it looms
Indeed, existing concrete classes (which may not be under the interface designers’ control) need to be modified to reflect the new interface contract as shown below , we need to implement new method 2 in the concrete implementation.
This situation is particularly problematic because the Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List interface that you used in previous chapters
Now all the concrete implementation need to provide the definition of sort() method, this is a breaking change.
Solution is the Default Methods:
In order to solve this problem Java 8 introduced a new mechanism to tackle this problem.
It may sound surprising, but since Java 8 interfaces can declare methods with implementation code in two ways.
First, Java 8 allowed static methods inside interfaces.
In other words, interfaces can now provide concrete implementation for methods. As a result, existing classes implementing an interface automatically inherit the default implementations if they don’t provide one explicitly, which allows you to evolve interfaces nonintrusively. You’ve been using several default methods all along. Two examples you’ve seen are sort in the List interface and stream in the Collection interface.
Please share if you liked my content. Also consider supporting me if you want me to keep creating content.