I am trying to understand the Consumer interface of Java. I have replicated it. But it throws StackOverflowError when i replace the lambda expression in return statement of andThen() method with anonymous class definition:
interface Interface<T> {
void accept(T t);
default Interface<T> andThen(Interface<T> after) {
//return (T t)->{accept(t); after.accept(t);};//this runs correctly
//below is the anonymous class definition of above lambda expression
return new Interface<T>(){
@Override
public void accept(T t)
{
accept(t); //stackoverflow error thrown
after.accept(t);
}
};
}
}
//Main class:
public class Lambda2 {
public static void main(String args[]) {
Interface<String> e1=str -> System.out.println("in e1 - "+str);
Interface<String> e2=str -> System.out.println("in e2 - "+str);
Interface<String> e3 = e1.andThen(e2);
e3.accept("Sample Output");
}
}
Could you please let me know why the lambda expression of the anonymous class definition does not cause StackOverflowError?