Default and Static Method
Default and Static Method
These were introduced in Java 8 to add new methods in interfaces without breaking existing
code.
✅ Example:
interface MyInterface {
void show(); // abstract method
✅ Output:
Implementing show()
Hello from default method!
✅ Example:
interface MyInterface {
static void display() {
System.out.println("Hello from static method!");
}
}
✅ Output:
🧠 Summary Table
An example where a Java interface contains both a default method and a static method,
along with a class that implements it.
// Default method
default void greet() {
System.out.println("Hello from default method!");
}
// Static method
static void staticGreet() {
System.out.println("Hello from static method!");
}
}
✅ Output:
Implementing show()
Hello from default method!
Hello from static method!
🔍 Explanation:
You want to provide optional behavior (via default) to all implementing classes
You want utility/helper methods (via static) directly in the interface
see how multiple interfaces with default methods are handled (like in diamond problem
cases)?
multiple interfaces with default methods — including the diamond problem in Java — and
how it's handled.
interface A {
default void show() {
System.out.println("Show from Interface A");
}
}
interface B {
default void show() {
System.out.println("Show from Interface B");
}
}
✅ Output:
Show from MyClass (resolving conflict)
🔍 Explanation:
A.super.show();
✅ Output:
All in the same interface, and show how a class uses them.
✅ Output:
Hello, John
Custom greeting from MyClass!
This is a static method in interface.
🧠 Summary: