In Java 8, interfaces were enhanced significantly with the introduction of default methods and static methods. Earlier, interfaces could only declare abstract methods (implicitly public abstract
) and constants (implicitly public static final
).
🔹 1. Default Methods in Interfaces
A default method is a method in an interface that has a body and uses the keyword default
.
✅ Key Points:
- Introduced to provide backward compatibility so old interfaces can evolve without breaking classes that implement them.
- They are inherited by implementing classes if not overridden.
- Can be overridden in the implementing class.
📌 Example:
interface MyInterface {
void normalMethod();
// Default method with implementation
default void defaultMethod() {
System.out.println("This is a default method in the interface.");
}
}
class MyClass implements MyInterface {
@Override
public void normalMethod() {
System.out.println("Implementing normal method.");
}
// Optional: Override default method
@Override
public void defaultMethod() {
System.out.println("Overridden default method in class.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.normalMethod(); // Implementing normal method.
obj.defaultMethod(); // Overridden default method in class.
}
}
🔹 2. Static Methods in Interfaces
A static method inside an interface is similar to a static method in a class.
✅ Key Points:
- Belongs to the interface itself, not to the objects of implementing classes.
- Cannot be overridden by implementing classes.
- Must be called using the interface name.
📌 Example:
interface MyInterface {
static void staticMethod() {
System.out.println("This is a static method in the interface.");
}
}
public class Main {
public static void main(String[] args) {
// Calling static method using interface name
MyInterface.staticMethod();
}
}
🔹 Difference Between Default and Static Methods
Feature | Default Method | Static Method |
---|---|---|
Belongs to | Instance of implementing class | Interface itself |
Inheritance | Inherited by implementing classes | Not inherited |
Override | Can be overridden | Cannot be overridden |
Call syntax | obj.methodName() | InterfaceName.methodName() |