Master Core Java Step-by-Step!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!
Subscribe Now on YouTubeUnderstanding Default Methods in Java Interfaces
Prior to Java 8, interfaces could only declare abstract methods—methods without any body. If you added a new method to an existing interface, every single implementing class was forced to implement it, breaking backward compatibility across established codebases.
To solve this challenge, Java introduced default methods (also called defender methods or virtual extension methods). They enable you to add new method implementations directly inside an interface without breaking existing client classes.
Why Were Default Methods Introduced?
Default methods bring essential flexibility to interface design:
- Backward Compatibility: New functionalities can be added to public library interfaces (like Java's Collections framework) without breaking existing third-party code.
- Optional Method Implementation: Implementing classes can choose to inherit the default behavior as-is or override it with specialized logic.
- Interface Evolution: Interfaces can evolve smoothly over time as system requirements expand.
Code Example: Defining and Using a Default Method
// Interface with a default method
interface Vehicle {
void start(); // Abstract method
default void playHorn() { // Default method with body
System.out.println("Beep beep! Standard horn activated.");
}
}
// Implementing class inherits playHorn automatically
class Car implements Vehicle {
public void start() {
System.out.println("Car engine started.");
}
}
public class Test {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.playHorn(); // Uses default interface implementation
}
}
Output:
Beep beep! Standard horn activated.
Core Rules for Default Methods
- Default methods must use the
defaultkeyword in their signature and provide a complete method body{ }. - They are public by default, so omitting the access modifier still keeps them accessible to implementing classes.
- If a class implements two interfaces sharing the exact same default method signature, the implementing class must explicitly override the method to resolve ambiguity.
No comments:
Post a Comment