Default Method in Interface Java: What It Is and How It Works
default method in a Java interface is a method with a body that provides a default implementation. It allows interfaces to have behavior without breaking existing classes that implement them. This feature was introduced in Java 8 to enable adding new methods to interfaces while maintaining backward compatibility.How It Works
Imagine an interface as a contract that says what methods a class must have, but without saying how they work. Before Java 8, interfaces could only declare methods without any code inside. This meant if you wanted to add a new method to an interface, all classes that use it had to update their code.
With default methods, interfaces can now provide a basic implementation for a method. This is like giving a default recipe that classes can use or override if they want. It helps keep old code working even when the interface changes.
Example
This example shows an interface with a default method and a class that uses it without changing anything.
interface Greeting { default void sayHello() { System.out.println("Hello from the interface!"); } } class Person implements Greeting { // No need to override sayHello() } public class Main { public static void main(String[] args) { Person p = new Person(); p.sayHello(); } }
When to Use
Use default methods when you want to add new functionality to interfaces without forcing all existing classes to implement the new methods immediately. This is especially useful in large projects or libraries where changing interfaces can break many classes.
For example, if you have an interface used by many classes and you want to add a new helper method, making it a default method lets old classes keep working while new classes can override it if needed.
Key Points
- Default methods allow interfaces to have method bodies.
- They help maintain backward compatibility when interfaces evolve.
- Classes can use the default implementation or override it.
- Introduced in Java 8.