Default methods in interfaces were introduced in Java 8 to allow interfaces to have method implementations while maintaining backward compatibility with older versions of Java, where interfaces could only declare method signatures (without implementations).

Key Points about Default Methods

  1. Definition:
    • A default method is a method in an interface that has a body (implementation), and it is declared using the default keyword.
    interface MyInterface {
        default void greet() {
            System.out.println("Hello, World!");
        }
    }
    
  2. Backward Compatibility:
    • Default methods allow you to add new methods to interfaces without breaking existing classes that implement those interfaces. Older classes will still work without needing to implement the new method.
  3. Multiple Implementations:
    • If a class implements multiple interfaces with default methods having the same signature, the class must explicitly override the method to resolve the conflict.
    interface A {
        default void show() {
            System.out.println("A");
        }
    }
    
    interface B {
        default void show() {
            System.out.println("B");
        }
    }
    
    class MyClass implements A, B {
        @Override
        public void show() {
            System.out.println("C");
        }
    }
    
  4. Purpose:
    • They were introduced to support functional programming features, such as lambda expressions and streams, by enabling interfaces to have concrete methods and reduce the need for abstract base classes.

Why were Default Methods Introduced in Java 8?

  • To evolve APIs: Default methods help evolve interfaces by allowing them to add new methods without breaking existing implementations.
  • Enabling functional programming: Default methods make it easier to introduce default behavior for new operations in functional interfaces (e.g., java.util.function interfaces).
  • Avoiding abstract classes: In cases where multiple interfaces need to provide a default implementation, default methods offer a way to avoid the need for abstract base classes.

In summary, default methods allow interfaces to provide method implementations, enhancing backward compatibility and enabling functional programming features in Java 8.