Java 8 changes required the introduction of default methods in interfaces.
/**
* One of the biggest changes in Java 8 is to collections library.
*
* It required the introduction of a new concept, ...
* default methods in interfaces.
*
* A dfault methods allows body implementations.
* Classes implementations win over default methods.
*/package com.minte9.lambdas.default_methods;
publicclassDefaultMethod{
publicstaticvoidmain(String[] args){
new A().hello(); // Hello defaultnew B().hello(); // Hello B
}
}
interfaceMyInterface{
publicdefaultvoidhello(){
System.out.println("Hello default");
}
}
classAimplementsMyInterface{ // Look Here// no implementation
}
classBimplementsMyInterface{
@Overridepublicvoidhello(){
System.out.println("Hello B");
}
}
Functional
Default methods can be used in lambda expresions.
/**
* Default methods can be used in lambda expresions.
* Functional interface must contain only one abstract method.
*/package com.minte9.lambdas.default_methods;
import java.util.Arrays;
import java.util.List;
publicclassFunctional{
publicstaticvoidmain(String[] args){
List<MyValue> myList = Arrays.asList(
() -> 1,
() -> 3,
() -> 2// lambda: get()
);
int maxDoubled = myList.stream()
.mapToInt(x -> x.getDouble()) // lambda: default method
.max()
.orElse(0)
;
System.out.println(maxDoubled); // 6
}
}
@FunctionalInterfaceinterfaceMyValue{
intget(); // abstractdefaultintgetDouble(){
return get() * 2;
}
}
Object
Default methods can be accessed only with object references!
/**
* Calling a default method in lambas without object reference ...
* doesn't work!
*/package com.minte9.lambdas.default_methods;
importstatic org.junit.Assert.assertEquals;
publicclassObject{
publicstaticvoidmain(String[] args){
Formula a = x -> x * 2;
assertEquals(4, a.calculate(2));
// pass
Formula b = x -> a.sqrt(x); // Look Here
assertEquals(4, b.calculate(16));
// pass//Formula c = x -> sqrt(x); // Not working
}
}
@FunctionalInterfaceinterfaceFormula{
abstractintcalculate(int x);
defaultintsqrt(int x){
return (int) Math.sqrt(x);
}
}
Super
Be careful when using multiple implementations and default method.
/**
* Interfaces are subject to multiple inheritance.
* Java compiler might not know which method to choose.
*
* In this case you must override the defaul method ...
* and provide the choosen interface method
*/package com.minte9.lambdas.default_methods;
publicclassSuper{
publicstaticvoidmain(String[] args){
String msg = new myClass().hello();
System.out.println(msg);
// Hello A
}
}
interfaceAI{
publicdefault String hello(){ return"Hello A"; }
}
interfaceBI{
publicdefault String hello(){ return"Hello B"; }
}
classmyClassimplementsAI, BI{
@Overridepublic String hello(){
return AI.super.hello(); // Look Here
}
}