Java 8 introduced a major enhancement to interfaces by allowing default and static methods. This made interfaces more powerful by enabling them to have method implementations.
Let’s understand both in a simple way.
🔹 What is a Default Method?
A default method is a method inside an interface that has a body (implementation).
👉 It is declared using the default keyword.
💡 Example:
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting");
}
}
class Car implements Vehicle {
// No need to override start()
}
🔹 Why Default Methods?
Before Java 8:
Interfaces could only have abstract methods
Adding a new method would break existing implementations
👉 Default methods solve this by providing a default implementation.
✅ Advantages:
Backward compatibility
No need to change existing classes
Improves code reusability
🔹 What is a Static Method in Interface?
A static method in an interface belongs to the interface itself.
👉 It is declared using the static keyword.
💡 Example:
interface MathUtil {
static int add(int a, int b) {
return a + b;
}
}
class Test {
public static void main(String[] args) {
int result = MathUtil.add(10, 20);
System.out.println(result);
}
}
🔹 Key Differences
🔹 Important Points
✅ 1. Default Methods Can Be Overridden
class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike is starting");
}
}
✅ 2. Static Methods Cannot Be Overridden
MathUtil.add(5, 10);
✅ 3. Multiple Interface Conflict
If two interfaces have the same default method, the implementing class must override it.
interface A {
default void show() {
System.out.println("A");
}
}
interface B {
default void show() {
System.out.println("B");
}
}
class Test implements A, B {
public void show() {
System.out.println("Resolved conflict");
}
}
🔹 Real-Time Use Cases
Adding new features to existing APIs
Utility methods inside interfaces
Supporting functional programming
Enhancing Java Collections Framework
🚀 Final Thoughts
Default and static methods changed how interfaces work in Java. They allow developers to write more flexible, maintainable, and backward-compatible code.
🎯 Learn More – Upgrade Your Java Skills
Join the Best Core JAVA Online Training in Hyderabad and gain hands-on experience with real-time projects, expert guidance, and interview preparation.


No comments:
Post a Comment