Forming a Stack Class Via Composition Rather Than Inheritance

A better way to implement a stack class is by reusing a list class through composition. Figure 21.12 uses a private List<T> (line 7) in class StackComposition<T>’s declaration. Composition enables us to hide the List<T> methods that should not be in our stack’s public interface. We provide public interface methods that use only the required List<T> methods. Implementing each stack method as a call to a List<T> method is called delegation—the stack method invoked delegates the call to the appropriate List<T> method. In particular, StackComposition<T> delegates calls to List<T> methods insertAtFront, removeFromFront, isEmpty and print. In this example, we do not show class StackCompositionTest ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.