Java Language Default Methods Accessing other interface methods within default method

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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());


Got any Java Language Question?