Default Method Syntax
What you'll learn: How to write default methods in interfaces using the default keyword to provide concrete implementations.
The Core Idea
In previous lessons, you learned why default methods exist—they let you add new functionality to interfaces without breaking existing implementations. Now let's see how to write them.
A default method is declared in an interface using the default keyword, followed by a complete method implementation (body included). This differs from traditional abstract interface methods, which have no body.
Basic Syntax
public interface MyInterface {
// Abstract method (no body)
void mustImplement();
// Default method (with body)
default void optionalMethod() {
System.out.println("This is a default implementation");
}
}
The syntax follows this pattern:
- Use the
defaultkeyword before the return type - Provide a method signature like any normal method
- Include curly braces
{}with a complete implementation
Key Rules
- Default methods must have a body (implementation)
- They are
publicby default (like all interface methods) - Classes implementing the interface can override them, but don't have to
- You can call other interface methods (abstract or default) from within a default method
Example in Context
public interface Drawable {
void draw(); // Abstract - must be implemented
default void display() {
System.out.println("Displaying...");
draw(); // Calls the abstract method
System.out.println("Done!");
}
}
Key Takeaway: Default methods use the default keyword followed by a complete method body, providing optional functionality that implementing classes inherit automatically.