Exercise 5

Extend the program “stack” (from Exercise 4) with a sub class of the class Stack (inherited from class Stack) called DebugStack, in which:

  • The constructor of DebugStack waits for a name String which is stored in a field.

  • When the constructor is called, it prints out a message: “DebugStack XYZ is initialized”.

  • It rewrites the methods “push” and “pop” such that they print out debug messages, too:
    -  “String blabla is inserted into the DebugStack XYZ
    -  “String blabla is removed from the DebugStack XYZ

Then the modified main program applies two DebugStack Objects


Exercise 6

1. Improve your stack implementation:

  • Arrange the different Stack classes into a stack package and its tests into a test package
  • Create a Stack interface with
    - push(String s), pop(), isEmpty(), toString() and
    - clear() removes all values from the stack
    - exch() exchange the first/top and the second elements in the stack.
    - peek() returns with the top element of the stack, but does not remove it.
  • Create abstract class AbstractStack implements Stack
    -  Leave push, pop, toString and isEmpty as abstract methods.
    -  Implement clear, exch and peek with calling abstract methods.

2. Rename the initial stack class (which is called Stack as well and) which was implemented first (in Exercise 4.) to BoundedStack:

  • Extends AbstractStack
  • Inherits the new methods from AbstractStack.
  • Define and throw exceptions for empty/full stack.
  • In test package, try out and check the new methods (use the interface Stack as an expected argument type).
  • In test, create errors (e.g.: pop from an empty stack, or push into a full stack) and handle the exceptions.

3. Reimplement DebugStack with delegation instead of inheritance (expect a class which implements the interface Stack):

  • Constructor: DebugStack(String name, Stack delegate).

  • Store the reference for the delegate in a private field.

  • All operations are performed on the delegate, but the with the debugging-versions of the methods.

  • Take care! DebugStack does not have any super class anymore (no inheritance), rather you should implement new methods with delegation (its methods work with the data field delegate given as the second argument of the constructor).Test the newly implemented BoundedStack and DebugStack classes in separate test programs..

Test the new class DebugStack with class BoundedStack.

Last modified: Wednesday, 26 March 2014, 3:11 PM