Search code examples
javajava-8functional-interface

How to create abstract Function using java 8


I am trying to implement a pipeline design pattern using Java 8 with the below article for my reference:

https://stackoverflow.com/a/58713936/4770397

Code:

public abstract class Pipeline{
Function<Integer, Integer> addOne = it -> {
        System.out.println(it + 1);
        return it + 1;
    };

Function<Integer, Integer> addTwo = it -> {
        System.out.println(it + 2);
        return it + 2;
    };

Function<Integer, Integer> timesTwo = input -> {
        System.out.println(input * 2);
        return input * 2;
    };

final Function<Integer, Integer> pipe = sourceInt
    .andThen(timesTwo)
    .andThen(addOne)
    .andThen(addTwo);
}

I am trying to add one abstract method & want to override it.
I am trying to do something like:

abstract BiFunction<Integer, Integer,Integer> overriden; 

and change pipe to:

final Function<Integer, Integer> pipe = sourceInt
    .andThen(timesTwo)
    .andThen(overriden)
    .andThen(addOne)
    .andThen(addTwo);
}

But the problem is, I don't know to declare a Function<Integer, Integer> as an abstract method.


Solution

  • You can just declare a regular abstract method that takes an Integer and returns an Integer and use the method reference syntax to refer to it:

    public abstract Integer overridden(Integer input);
    
    final Function<Integer, Integer> pipe = sourceInt
        .andThen(timesTwo)
        .andThen(this::overridden)
        .andThen(addOne)
        .andThen(addTwo);