Tutorial by Examples

/** * Interface with default method */ public interface Printable { default void printString() { System.out.println( "default implementation" ); } } /** * Class which falls back to default implementation of {@link #printString()} */ public class WithDefault...
You can as well access other interface methods from within your default method. public interface Summable { int getA(); int getB(); default int calculateSum() { return getA() + getB(); } } public class Sum implements Summable { @Override public int get...
In classes, super.foo() will look in superclasses only. If you want to call a default implementation from a superinterface, you need to qualify super with the interface name: Fooable.super.foo(). public interface Fooable { default int foo() {return 3;} } public class A extends Object impl...
The simple answer is that it allows you to evolve an existing interface without breaking existing implementations. For example, you have Swim interface that you published 20 years ago. public interface Swim { void backStroke(); } We did a great job, our interface is very popular, there ar...
Implementations in classes, including abstract declarations, take precedence over all interface defaults. Abstract class method takes precedence over Interface Default Method. public interface Swim { default void backStroke() { System.out.println("Swim.backStroke"); ...
Consider next example: public interface A { default void foo() { System.out.println("A.foo"); } } public interface B { default void foo() { System.out.println("B.foo"); } } Here are two interfaces declaring default method foo with the same signature. If you wi...

Page 1 of 1