Java.Java8.What are the default methods of an interface?

✅ 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

ConceptDescription
✅ Defined in interfaceYes — uses default keyword
✅ Has method bodyYes
✅ Can be overriddenYes — implementing class can override it
❌ Can’t override Object methodsYou can’t define default equals(), hashCode(), etc. in an interface
✅ Used in multiple inheritanceYes, 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

FeatureDefault Methods in Interfaces
🧱 PurposeAdd method bodies to interfaces (Java 8+)
💬 Syntaxdefault keyword inside interface
🔄 Overrideable?Yes — implementing classes can override
🧠 BenefitEvolve APIs without breaking existing code
This entry was posted in Без рубрики. Bookmark the permalink.