CSE143 Sample Inheritance Program handout #29
Stack Interface
---------------
public interface Stack {
public void push(E value);
public E pop();
public boolean isEmpty();
}
SimpleStack Implementation
--------------------------
import java.util.*;
public class SimpleStack implements Stack {
private ArrayList data;
public SimpleStack() {
data = new ArrayList();
}
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 extends Stack {
public int length();
public E peek();
}
ComplexStack implementation of ExtendedStack
--------------------------------------------
public class ComplexStack extends SimpleStack
implements ExtendedStack {
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 s1 = new SimpleStack();
loadStack(s1);
printStack(s1);
ExtendedStack s2 = new ComplexStack();
loadStack(s2);
System.out.println("length = " + s2.length());
System.out.println("peek = " + s2.peek());
printStack(s2);
}
public static void loadStack(Stack 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 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