1. Introduction
Java 8 introduced new capabilities to interfaces, including default methods and static methods.
A default method in a Java interface is a method with a body that provides a default implementation. It can be overridden in classes that implement the interface.
A static method, on the other hand, is associated with the interface itself rather than any object that implements the interface and cannot be overridden by implementing classes.
2. Key Points
1. Default methods help to add new functionality to interfaces without breaking the existing implementation of the interface.
2. Static methods in interfaces cannot be overridden and are not inherited by implementing classes.
3. Default methods can be accessed by instances of implementing classes and can be overridden by these classes.
4. Static methods are meant to provide utility functions related to the interface.
3. Differences
Default Method | Static Method |
---|---|
Can be overridden by implementing classes. | Cannot be overridden by implementing classes. |
Associated with an instance of a class that implements the interface. | Associated with the interface itself, not the instance. |
Helps to evolve interfaces without breaking existing code. | Provides utility functions that can be called without an object instance. |
4. Example
// Example of an interface with a default method and a static method
interface MyInterface {
// Default method
default void displayDefault() {
System.out.println("Default Method Executed");
}
// Static method
static void displayStatic() {
System.out.println("Static Method Executed");
}
}
class MyClass implements MyInterface {
// Overriding the default method
public void displayDefault() {
System.out.println("Overridden Default Method Executed");
}
}
public class Main {
public static void main(String[] args) {
MyInterface myInterface = new MyClass();
// Default method is called - overridden version
myInterface.displayDefault();
// Static method is called
MyInterface.displayStatic();
}
}
Output:
Overridden Default Method Executed Static Method Executed
Explanation:
1. MyClass implements MyInterface and overrides its displayDefault method.
2. When displayDefault is called on an instance of MyClass, the overridden method is executed.
3. The static method displayStatic is called directly on the interface and executes the method defined in the interface.
5. When to use?
- Use default methods to add new methods to an interface without breaking existing implementations.
- Use static methods when you need methods related to an interface, but not tied to an instance of the interface.
Comments
Post a Comment
Leave Comment