Java 8 brought a new capability known as default methods into Java interface. This articles guides you how to get the benefit from default methods in interface.
Why Default Methods in Interfaces Are Needed
Imagine in a situation where if one or more methods are added to the interface, then classes which implemented those interfaces would have to rewrite their implementations. Prior to the introduction of default methods capability in interface, there is this soi-disant “Extended Interface” to resolve the above-mentioned problem.
Default methods enable programmers to add new functionality to the interfaces of your libraries that are automatically available in the implementations. In this way, backward compatibility is neatly preserved without having to refactor classes which implemented the going-to-be-modified interface.
Default Interface Methods in Action
package com.cloudberry.my;
public interface Vehicle{
String getBrand();
String speedUp();
String slowDown();
default String turnAlarmOn() {
return "Turning Vehicle alarm on.";
}
default String turnAlarmOff() {
return "Turning Vehicle alarm off.";
}
}
There are 2 default methods namely turnAlarmOn()
& turnAlarmOff()
in interface Vehicle
.
package com.cloudberry.my.action;
import com.cloudberry.my.Vehicle;
public class Bus implements Vehicle{
@Override
public String getBrand() {
return "Alex Dennis";
}
@Override
public String speedUp() {
return "200kmph";
}
@Override
public String slowDown() {
return "0kmph";
}
}
Because of class Bus
implements the interface Vehicle , therefore turnAlarmOn()
& turnAlarmOff()
are automatically provided by interface Vehicle
.
package com.cloudberry.my.action;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.cloudberry.my.Vehicle;
class BusTest {
@Test
void testBus() {
Bus bus = new Bus();
assertEquals("Turning Vehicle alarm off.", bus.turnAlarmOff());
}
@Test
void testVehicle() {
Vehicle bus = new Bus();
assertEquals("Turning Vehicle alarm off.", bus.turnAlarmOff());
}
}
FYI, the above unit-test results are pass. Even though Bus
does not have turnAlarmOff()
method, but because of Bus
implements interface Vehicle
which the interface marks the turnAlarmOff()
as default method, thus every instance of Bus
contains the default methods which it implements from.