Search code examples
javainheritanceliststackcomposition

java inheritance versus composition (implementing a stack)


I am trying to implement a Stack in java (using the list interface: Interface List).

I want to implement it two different ways: using composition and inheritance.

For inheritance, so far I have:

 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;

 public class StackInheritance implements List {
      //implement list methods
 }

For composition, I have:

 import java.util.List;

 public abstract class StackComposition implements List {
     // implement some standard methods
 }

 public class StackViaList extends StackComposition {
     // implement methods that have not been implemented in the abstract
     // class
 }

I am confused as to where to go from here. I have never used an interface before, so am I supposed to use the List methods to "mimic" a stack, using an Array or an ArrayList for example?

Also, for composition, I don't understand what methods should go into StackComposition and what should go into StackViaList. Between not fully understanding interfaces as well as inheritance and composition, I'm a bit lost. I can't seem to just "get it" yet...

Any help would be appreciated, thanks!


Solution

  • For composition, the stack class should HAVE a list, not implement or extend a List-based class. Inheritance is an "IS A" relationship, whereas composition is a "HAS A" relationship.

    For example:

    public class StackWithComposition
    {
        // StackWithComposition HAS A List (rather than IS A List)
        private List myList = new ArrayList();
    
        public void push(object item)
        {
            // add item to myList, etc.
        }
    
        public object pop()
        {
            // return item at top (or end) of myList
        }
    
        // etc.
    }
    

    Note that you would probably want to make this a generic class, rather than dealing with raw objects, but this would be the idea.

    In this case, the composition-based solution is probably preferable over the inheritance-based solution. When you inherit from a class/interface, you should ask yourself, is the Stack a List? Most Stacks should not provide the user with access to all the raw List methods, so it's better to hide the face that you're using a List as the internal data structure. Using a composed List allows you to completely hide the fact that you're using a List as the internal structure.