Java 8 Features Default and static methods in interfaces

One of the major changes introduced in Java 8 was the ability to define default and static methods in interfaces. Prior to Java 8, interfaces could only contain abstract method declarations, which meant that any implementation had to be provided by a class that implemented the interface. With the introduction of default and static methods, interfaces can now provide a default implementation for a method, which can be overridden by a class that implements the interface, or a static method that can be called directly on the interface itself.

Default methods:
A default method is a method defined in an interface with a default implementation. When a class implements an interface with a default method, it can choose to override the default implementation or use it as is. Default methods are marked with the “default” keyword and can be called on an instance of the implementing class.

For example, let’s say we have an interface called “Shape” with a default method called “calculateArea()” that returns 0.0:

public interface Shape {
    default double calculateArea() {
        return 0.0;
    }
}

Now, when a class implements the Shape interface, it can choose to override the default implementation of the calculateArea() method or use the default implementation:

public class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

In this example, the Circle class overrides the default implementation of the calculateArea() method with its own implementation that calculates the area of a circle.

Static methods:
A static method is a method defined in an interface that can be called directly on the interface itself, without the need for an instance of a class that implements the interface. Static methods are marked with the “static” keyword.

For example, let’s say we have an interface called “MathUtils” with a static method called “max()” that takes two integers and returns the maximum value:

public interface MathUtils {
    static int max(int a, int b) {
        return a > b ? a : b;
    }
}

Now, we can call the max() method directly on the MathUtils interface:

int max = MathUtils.max(5, 7);

In this example, we don’t need to create an instance of a class that implements the MathUtils interface to call the max() method. We can call it directly on the interface itself.