public interface Stack { T top(); Stack pop(); Stack push(T newTop); default Stack push(T newTop) { return new NonEmpty<>(newTop, this); } public class Empty implements Stack { public T top() { throw new EmptyStackException(); } public Stack pop() { throw new EmptyStackException(); } } public class NonEmpty implements Stack { private T top; private Stack tail; public NonEmpty(T newTop, Stack previous) { top = newTop; tail = previous; } public T top() { return top; } public Stack pop() { return tail; } } }