Java Reference
In-Depth Information
Implementing Abstract Classes via Lambdas
Lambdas and interfaces go hand in hand in Java 8. They are really two different syntaxes for the same
underlying functionality. However, abstract classes can also get some help from the addition of lambdas.
The syntax is not as nice, but it is more clear than the classic inline class definition.
Like with interfaces, the goal is going to be to reduce the implementation of all the undefined methods
into a single statement. In this case, however, we will be attempting to build a constructor that takes a
lambda instead of simply a lambda. The user will have to call our constructor (which is less nice), but this
gives us significantly more to work with: in addition to the implementation lambda, we can also accept other
configuration values.
To see how this works specifically, let's look at AbstractCollection . Let's say that we wanted
to be able to implement an AbstractCollection through a lambda. The two abstract methods on
AbstractCollection are the following:
public abstract Iterator<E> iterator()
public abstract int size()
We will want to implement both of those by passing a lambda and possibly some other arguments
into a constructor. We can certainly accept the size as an argument in the constructor, which leaves the
iterator() method for our lambda implementation. We will therefore require the user to provide us
something like a Supplier<Iterator<E>> as our lambda argument. Of course, we will provide an interface
type for that supplier, so that users understand exactly what we need. We will call this kind of a Collection ,
LambdaCollection .
To demonstrate using our LambdaCollection , let's consider that we wanted to be able to treat the lines
of a file as a Collection, and we were willing to do it in an inefficient (yet effective) way. In that case, we could
define a way to go from the lines of the files to an iterator over the lines of the files, and this would be our
lambda. We would also have to do one trip through the file at the outset to get the size. We demonstrate the
code for LambdaCollection and this case in Listing 7-13.
Listing 7-13. Using a Lambda to Implement an Abstract Type
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
public class Listing14 {
public static class LambdaCollection<E> extends AbstractCollection<E> {
private final int size;
private final Listing14.LambdaCollection.IteratorFactory<E> factory;
* Defines the means of acquiring an {@link java.util.Iterator}.
public interface IteratorFactory<E> {
Search WWH ::

Custom Search