Sobes.tech
Junior — Middle

What does the appearance of default methods in Java interfaces mean and how are they implemented?

sobes.tech AI

Answer from AI

Default methods in Java interfaces appeared starting from Java 8. They allow adding method implementations directly in the interface without breaking backward compatibility with existing classes that implement this interface.

Implementation:

  • A method in an interface is declared with the default keyword and contains a body.
  • Classes implementing the interface can use this method without overriding it or override it if necessary.

Example:

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

public class MyClass implements MyInterface {
    // Can choose not to implement defaultMethod, as it already exists
}

This allows extending interfaces without the need to change all classes that implement them.