Gyh's Braindump

Java Interface

tags
Interface
source
DT-On Java 8

Grammar

positioneaseboxintervaldue
front2.5002021-01-24T08:26:03Z
  • don’t have to use abstract keyword
  • after java 8, allow default methods (default implementation)
  • after java 8, allow static methods
  • can be public, if that interface is defined in a file of the same name
  • methods are public, so implementation of derived classes’s methods must be public, too
public interface PureInterface {
    int m1();
    void m2();
    double m3();
}

Default Method

positioneaseboxintervaldue
front2.5002021-01-24T08:26:11Z

Define a default implementation for methods in interfaces. The compelling reason if default is that it allows new methods added without breaking all the code that uses that interface.

interface InterfaceWithDefault {
    void firstMethod();
    void secondMethod();
    default void newMethod() {
        System.out.println("newMethod");
    }
}

Links to this note