Sobes.tech
Junior — Middle

What is the purpose of implementing a default method inside an interface in Java?

sobes.tech AI

Answer from AI

In Java, default implementation of a method inside an interface (default method) was introduced starting from Java 8 to provide a body for methods directly in the interface. This was done to ensure backward compatibility when extending interfaces.

Main purposes of default methods:

  • Allow adding new methods to interfaces without breaking existing implementations.
  • Provide a base implementation that can be overridden in classes.

Example:

public interface MyInterface {
    default void defaultMethod() {
        System.out.println("This is a default method");
    }
}

public class MyClass implements MyInterface {
    // Can use default implementation or override
}

Thus, default methods increase flexibility of interfaces and simplify API evolution.

What is the purpose of implementing a default method… - sobes.tech