In Java 8, a new feature called default Methods was introduced in interfaces. Before Java 8, interfaces could only contain abstract methods , and any class implementing the interface had to implement all methods.
Default methods in Java 8 allow interfaces to include methods with a body (implementation).
A default method is a method inside an interface that has a defined implementation using the default keyword.
- Defined inside an interface
- It has a method body
- They are not static
- It is not mandatory to override in implementing classes
- Backward Compatibility
- Code Reusability
- Interface Evolution
- Reduces code duplication
- Improves interface flexibility
- Maintains backward compatibility
- Allows adding new features without breaking code
Code Explanation (Step-by-Step)
- In this program we use an interface Test, which defines a calculate() and squareRoot() methods.
- The interface contains a calculate abstract method, which means:
- It has no implementation.
- It must be implemented by the user.
- The interface also contains a squareRoot default method, which means:
- It has a complete implementation.
- It is optional to override.
- The default method is used to perform a square root calculation operation.
- A DefaultMethodInterface main class is created to run the program.
- An object of the interface is created using an anonymous class.
- The anonymous class provides implementation only for the abstract method.
- Inside that implementation, the default method is reused instead of writing new logic.
- The program calls the abstract method through the object, which internally uses the default method.
- The program also directly calls the default method using the object.
- The output shows the result of both:
- Indirect call (via abstract method)
- Direct call (default method)
interface Test {
//Abstract method
double calculate(int a);
//Default method
default double squareRoot(int a) {
return Math.sqrt(a);
}
}
public class DefaultMethodInterface {
public static void main(String[] args) {
Test f = new Test() {
public double calculate(int a) {
return squareRoot(a);
}
};
System.out.println("calculate value is:- " + f.calculate(100));
System.out.println("Square value is:- " + f.squareRoot(16));
}
}
Output :-
calculate value is:- 10.0
Square value is:- 4.0
Can Default Methods Be Overridden?
Yes, default methods can be overridden in implementing classes.
class MyClass implements Test {
public double calculate(int a) {
return a * 2;
}
@Override
public double squareRoot(int a) {
return a; // custom implementation
}
}