In the Collection Interface I found a method named removeIf()
that contains its implementation.
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
I want to know if there is any way to define method body in an interface?
What is the default
keyword and how does it work?
From https://dzone.com/articles/interface-default-methods-java
Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that 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 hear about the new feature for the first time:
What if the class implements two interfaces and both those interfaces define a default method with the same signature?
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 Clazz implements A, B {
}
This code fails to compile with the following result:
java: class Clazz inherits unrelated defaults for foo() from types A and B
To fix that, in Clazz, we have to resolve it 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 method foo() from interface A instead of implementing our own.
It is possible to refer to A#foo() as follows:
public class Clazz implements A, B {
public void foo(){
A.super.foo();
}
}