CSE143 Sample Inheritance Program handout #29 Stack Interface --------------- public interface Stack<E> { public void push(E value); public E pop(); public boolean isEmpty(); } SimpleStack Implementation -------------------------- import java.util.*; public class SimpleStack<E> implements Stack<E> { private ArrayList<E> data; public SimpleStack() { data = new ArrayList<E>(); } public void push(E value) { data.add(value); } public E pop() { return data.remove(data.size() - 1); } public boolean isEmpty() { return data.isEmpty(); } } ExtendedStack Interface ----------------------- public interface ExtendedStack<E> extends Stack<E> { public int length(); public E peek(); } ComplexStack implementation of ExtendedStack -------------------------------------------- public class ComplexStack<E> extends SimpleStack<E> implements ExtendedStack<E> { private int length = 0; public void push(E data) { length++; super.push(data); } public E pop() { length--; return super.pop(); } public E peek() { E value = super.pop(); super.push(value); return value; } public int length() { return length; } } Testing Program --------------- public class StackTest { public static void main(String[] args) { Stack<String> s1 = new SimpleStack<String>(); loadStack(s1); printStack(s1); ExtendedStack<String> s2 = new ComplexStack<String>(); loadStack(s2); System.out.println("length = " + s2.length()); System.out.println("peek = " + s2.peek()); printStack(s2); } public static void loadStack(Stack<String> s) { s.push("howdy"); for (int i = 0; i < 10; i++) s.push("" + (int) (Math.random() * 20)); s.push("doody"); } public static void printStack(Stack<String> s) { while (!s.isEmpty()) System.out.print(s.pop() + " "); System.out.println(); } } Output of Testing Program ------------------------- doody 14 2 12 4 8 7 18 6 16 16 howdy length = 12 peek = doody doody 17 3 6 2 17 13 9 15 14 9 howdy
Stuart Reges
Last modified: Fri Dec 2 16:35:08 PST 2005