Sitemap

Java 8: Default Methods

1 min readMar 8, 2021

Default methods are introduced in Java 8 to use with interfaces. This helps older interfaces to support lambda expressions without breaking their implementations.

Press enter or click to view image in full size
Photo by Jasinthan Yoganathan on Unsplash

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:

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!