Java 8: Default Methods
Default methods are introduced in Java 8 to use with interfaces. This helps older interfaces to support lambda expressions without breaking their implementations.
For example List interface do not have forEach method as this added in Java 8, adding it will break the implementations. By adding this a default implementation these old implementations also can support forEach method automatically.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
}As this new implementation can be a problem when used in multiple inheritance scenarios. If both has same method then we may have to create a new method to override both.
Get Nuwan Zen’s stories in your inbox
Join Medium for free to get updates from this writer.
An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}Ref: https://www.tutorialspoint.com/java8/java8_default_methods.htm
Read my other blogs:







