Overriding Default Methods
What you'll learn: You'll discover that classes can override default methods from interfaces to provide their own custom implementation instead of using the inherited one.
The Freedom to Customize
When a class implements an interface that contains a default method, the class doesn't have to use the default implementation. Just like overriding methods from a superclass, you can override default methods to provide behavior that's specific to your class.
Why Override a Default?
Sometimes the default behavior provided by an interface is fine for most implementations, but your particular class needs something different. That's where overriding comes in handy—you get the convenience of defaults when you need them, and the flexibility to customize when you don't.
How It Works
Overriding a default method follows the same rules as overriding any interface method:
interface Greetable {
default void greet() {
System.out.println("Hello from default!");
}
}
class FormalGreeter implements Greetable {
@Override
public void greet() {
System.out.println("Good day to you, esteemed colleague.");
}
}
class CasualGreeter implements Greetable {
// Uses the default implementation - no override needed
}
In this example, FormalGreeter provides its own implementation, while CasualGreeter inherits the default behavior. Both are valid approaches.
The Rules Still Apply
Remember: your override must be public (since all interface methods are public), and you can use the @Override annotation to catch mistakes.
Key Takeaway: Classes can override default methods just like regular methods, giving you the power to accept the default behavior or provide your own implementation—whichever suits your class's needs.