default methods
- Java course
- Intermediate
- Lesson 49/116
- 5 min
Learn default methods inside interfaces.
default methods
A default method is a method with a body inside an interface. The implementing class may override it; if not, the interface body is used. It starts with the default keyword.
Example: interface Logger { default void info(String msg) { System.out.println(msg); } }. Here info has a body. Even if the implementing class does not write info, this body runs. This is used to add methods to existing interfaces without breaking old classes. It is the safe way to add behavior to a contract. The class may still override the method if it wants.
Adding methods without breaking the interface
Default methods let you add behavior to existing interfaces. You can add new methods without changing implementing classes. This is critical for backward compatibility.
Example: if you add default void warn(String msg) to Logger, old classes work even without writing the method. New classes may override it if they want. Without default methods, adding a method to an interface breaks all implementing classes. This feature, added in Java 8, gives great flexibility to library authors. It is the official way to grow an interface without breaking old code.
Practice Add a default method to the Logger interface
Define an interface Logger. Add a default void info(String msg) method; its body runs System.out.println("Info: " + msg);. Then write class ConsoleLogger implements Logger; leave the body empty without writing info. In main call new ConsoleLogger().info("Logging started").
Starter code
// Define the Logger interface
// Add a default info method
// Write ConsoleLogger implements Logger, do not override info
// Call info in mainSample solution
interface Logger {
default void info(String msg) {
System.out.println("Info: " + msg);
}
}
class ConsoleLogger implements Logger {
}
class Main {
public static void main(String[] args) {
new ConsoleLogger().info("Logging started");
}
}Expected output
Info: Logging started
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if a default method is not written in the implementing class?
- It gives a compile error
- The method is deleted
- The interface body runs Correct answer
- It gives a runtime error
Explanation: The interface body is used.
2 Add the default keyword
interface Logger {
____ void info(String msg) {
System.out.println(msg);
}
}
interface Logger {
default void info(String msg) {
System.out.println(msg);
}
}
Explanation: The default keyword defines a bodyful interface method.
3 Match the default method concepts
| Term | Meaning |
|---|---|
default |
Bodyful method keyword |
info(String msg) |
Method signature |
override |
Rewrite |
backward compatible |
Backward compatible |