198. Default methods

Default methods were added to Java 8. Their main goal is to provide support for interfaces so that they can evolve beyond an abstract contract (contain only abstract methods). This facility is very useful for people that write libraries and want to evolve APIs in a compatible way. Via default methods, an interface can be enriched without disrupting existing implementations.

A default method is implemented directly in the interface and is recognized by the default keyword.

For example, the following interface defines an abstract method called area() and a default method called perimeter():

public interface Polygon {

public double area();

default double perimeter(double...segments) {
return Arrays.stream(segments)
.sum();
}
}

Since the perimeter of all common polygons (for example, squares) is the sum of the edges, we can implement it here. On the other hand, the area formula differs from polygon to polygon, and so a default implementation will not be very useful.

Now, let's define a Square class that implements Polygon. Its goal is to express the area of a square via the perimeter:

public class Square implements Polygon {

private final double edge;

public Square(double edge) {
this.edge = edge;
}

@Override
public double area() {
return Math.pow(perimeter(edge, edge, edge, edge) / 4, 2);
}
}

Other polygons (for example, rectangles and triangles) can implement Polygon and express the area based on the perimeter that's computed via the default implementation.

However, in certain cases, we may need to override the default implementation of a default method. For example, the Square class may override the perimeter() method, as follows:

@Override
public double perimeter(double...segments) {
return segments[0] * 4;
}

We can call it as follows:

@Override
public double area() {
return Math.pow(perimeter(edge) / 4, 2);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset