✅ What Are Default Methods?
A default method is a method defined in an interface with a body using the default
keyword.
🔧 Syntax:
public interface MyInterface {
default void greet() {
System.out.println("Hello from MyInterface");
}
}
Default methods are optional to override in implementing classes
They provide concrete behavior inside interfaces — something that was not allowed before Java 8
🧠 Why Were Default Methods Introduced?
Problem:
Before Java 8, adding a new method to an interface would break all implementations.
Solution:
Default methods let library designers add new methods to interfaces without breaking existing code.
For example:
interface List<E> {
default void sort(Comparator<? super E> c) {
Collections.sort(this, c);
}
}
Now all classes implementing List
(like ArrayList
) automatically get sort()
.
🔍 Example
interface Animal {
default void breathe() {
System.out.println("Breathing...");
}
}
class Dog implements Animal {
// No need to override breathe(), but can if desired
}
new Dog().breathe(); // Output: Breathing...
✨ Key Points
Concept | Description |
---|---|
✅ Defined in interface | Yes — uses default keyword |
✅ Has method body | Yes |
✅ Can be overridden | Yes — implementing class can override it |
❌ Can’t override Object methods | You can’t define default equals() , hashCode() , etc. in an interface |
✅ Used in multiple inheritance | Yes, but you must resolve conflicts manually |
⚔️ Conflict Example: Diamond Problem
interface A {
default void hello() { System.out.println("Hello from A"); }
}
interface B {
default void hello() { System.out.println("Hello from B"); }
}
class C implements A, B {
public void hello() {
A.super.hello(); // or B.super.hello()
}
}
You must override hello()
in C
to resolve the conflict.
✅ Summary
Feature | Default Methods in Interfaces |
---|---|
🧱 Purpose | Add method bodies to interfaces (Java 8+) |
💬 Syntax | default keyword inside interface |
🔄 Overrideable? | Yes — implementing classes can override |
🧠 Benefit | Evolve APIs without breaking existing code |