From https://dzone.com/articles/interface-default-methods-java
Java 8 introduces a new feature called βDefault Methodβ or (Defender Methods), which allows a developer to add new methods to interfaces without breaking existing implementation of these interfaces. This provides flexibility to allow the implementation of an interface definition that will be used by default in situations where a particular class cannot provide an implementation for this method.
public interface A { default void foo(){ System.out.println("Calling A.foo()"); } } public class ClassAB implements A { }
There is one common question that people ask about default methods when they first hear about a new feature:
What if a class implements two interfaces, and both of these interfaces define a default method with the same signature?
An example to illustrate this situation:
public interface A { default void foo(){ System.out.println("Calling A.foo()"); } } public interface B { default void foo(){ System.out.println("Calling B.foo()"); } } public class ClassAB implements A, B { }
This code does not compile with the following result:
java: class Clazz inherits unrelated defaults for foo() from types A and B
To fix this, in Clazz we need to resolve this manually by overriding the conflicting method:
public class Clazz implements A, B { public void foo(){} }
But what if we would like to call the default implementation of the foo () method from interface A instead of implementing our own.
A # foo () can be accessed as follows:
public class Clazz implements A, B { public void foo(){ A.super.foo(); } }
gifpif Aug 17 '13 at 8:57 2013-08-17 08:57
source share