CSE143 Inheritance Examples handout #33 Class StutterList.java ---------------------- // Variation of ArrayList that adds values twice with the appending add. import java.util.*; public class StutterList<E> extends ArrayList<E> { public boolean add(E value) { super.add(value); super.add(value); return true; } } Class MyPoint.java ------------------ // Variation of Point that keeps track of how many times each point has been // translated and that provides a getTranslateCount method. import java.awt.*; public class MyPoint extends Point { private int count; public MyPoint() { this(0, 0); } public MyPoint(int x, int y) { super(x, y); count = 0; } public void translate(int dx, int dy) { count++; super.translate(dx, dy); } public int getTranslateCount() { return count; } } Class PointTest.java -------------------- // Class that demonstrates simple use of the MyPoint class. public class PointTest { public static void main(String[] args) { MyPoint p = new MyPoint(13, 42); p.translate(3, 14); p.translate(72, 4); p.translate(-8, 9); System.out.println("Translate count = " + p.getTranslateCount()); } } Output of PointTest ------------------- Translate count = 3 Class UndoStack.java -------------------- // UndoStack is a variation of the Stack class that supports an undo operation // for reversing the effect of push and pop operations. The canUndo method // indicates whether an undo is legal. import java.util.*; public class UndoStack<E> extends Stack<E> { private Stack undoStack; // post: constructs an empty UndoStack public UndoStack() { undoStack = new Stack(); } // post: pushes and returns the given value on top of the stack public E push(E value) { super.push(value); undoStack.push("push"); return value; } // post: pops and returns the value at the top of the stack public E pop() { E value = super.pop(); undoStack.push(value); undoStack.push("pop"); return value; } // post: returns whether or not an undo can be done public boolean canUndo() { return !undoStack.isEmpty(); } // pre : canUndo() (throws IllegalStateException if not) // post: undoes the last stack push or pop command public void undo() { if (!canUndo()) { throw new IllegalStateException(); } if (undoStack.pop().equals("push")) { super.pop(); } else { super.push((E) undoStack.pop()); } } }
Stuart Reges
Last modified: Fri Nov 30 17:47:21 PST 2012