Java Language Accessing other interface methods within default method


Example

You can as well access other interface methods from within your default method.

public interface Summable {
    int getA();

    int getB();

    default int calculateSum() {
        return getA() + getB();
    }
}

public class Sum implements Summable {
    @Override
    public int getA() {
        return 1;
    }

    @Override
    public int getB() {
        return 2;
    }
}

The following statement will print 3:

System.out.println(new Sum().calculateSum());

Default methods could be used along with interface static methods as well:

public interface Summable {
    static int getA() {
        return 1;
    }

    static int getB() {
        return 2;
    }

    default int calculateSum() {
        return getA() + getB();
    }
}

public class Sum implements Summable {}

The following statement will also print 3:

System.out.println(new Sum().calculateSum());