Sobes.tech
Junior — Middle

How can methods be implemented in interfaces?

sobes.tech AI

Answer from AI

In Java, starting from version 8, interfaces can contain:

  • Abstract methods — without implementation, which must be implemented in classes.
  • Default methods — with implementation, which can be overridden but are not required.
  • Static methods — with implementation, called through the interface.

Example of implementing default and static methods in an interface:

public interface MyInterface {
    void abstractMethod(); // abstract method

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

    static void staticMethod() {
        System.out.println("This is a static interface method");
    }
}

Classes implementing the interface are required to implement abstract methods but can use or override default methods. Static methods are called directly through the interface.

How can methods be implemented in interfaces? — Java - sobes.tech