Default Methods in Interfaces in Java 8 Examples

JavaDZone
2 min readJun 22, 2024

--

Until Java 1.7, inside an interface, we could only define public abstract methods and public static final variables. Every method present inside an interface is always public and abstract, whether we declare it or not. Similarly, every variable declared inside an interface is always public, static, and final, whether we declare it or not. With the introduction of default methods in interfaces, it is now possible to include method implementations within interfaces, providing more flexibility and enabling new design patterns.

From Java 1.8 onwards, in addition to these, we can declare default concrete methods inside interfaces, also known as defender methods.

We can declare a default method using the keyword default as follows:

default void m1() {
System.out.println("Default Method");
}

Interface default methods are by default available to all implementation classes. Based on the requirement, an implementation class can use these default methods directly or override them.

Default Methods in Interfaces Example:

interface ExampleInterface {
default void m1() {
System.out.println("Default Method");
}
}

class ExampleClass implements ExampleInterface {
public static void main(String[] args) {
ExampleClass example = new ExampleClass();
example.m1();
}
}

Default methods are also known as defender methods or virtual extension methods. The main advantage of default methods is that we can add new functionality to the interface without affecting the implementation classes (backward compatibility).

Note: We can’t override Object class methods as default methods inside an interface; otherwise, we get a compile-time error.

Example:

interface InvalidInterface {
default int hashCode() {
return 10;
}
}

Compile-Time Error: The reason is that Object class methods are by default available to every Java class, so it’s not required to bring them through default methods.

For further detailed information, please visit: Default Methods in Interfaces in Java 8 — Examples

--

--

JavaDZone

I'm a senior software engineer specializing in Java Spring Boot Microservices. I'm also a dedicated blogger at javadzone.com where I share java/springboot, etc.