Java Reference
In-Depth Information
1
// Fig. 21.10: StackInheritance.java
2
// StackInheritance extends class List.
3
package
com.deitel.datastructures;
4
5
extends
List<T>
public
class
StackInheritance<T>
6
{
7
// constructor
8
public
StackInheritance()
9
{
10
super
(
"stack"
);
11
}
12
13
// add object to stack
14
public void
push(T object)
15
{
16
insertAtFront(object);
17
}
18
19
// remove object from stack
20
public
T pop()
throws
EmptyListException
21
{
22
return
removeFromFront();
23
}
24
}
// end class StackInheritance
Fig. 21.10
|
StackInheritance
extends class
List
.
structure. Lines 27-32 pop the objects from the stack in an infinite
while
loop. If method
pop
is invoked on an empty stack, the method throws an
EmptyListException
. In this
case, the program displays the exception's stack trace, which shows the methods on the
program-execution stack at the time the exception occurred. The program uses method
print
(inherited from
List
) to output the contents of the stack.
1
// Fig. 21.11: StackInheritanceTest.java
2
// Stack manipulation program.
3
import
com.deitel.datastructures.StackInheritance;
4
import
com.deitel.datastructures.EmptyListException;
5
6
public class
StackInheritanceTest
7
{
8
public static void
main(String[] args)
9
{
10
StackInheritance<Integer> stack =
new
StackInheritance<>();
11
12
// use push method
stack.push(
-1
);
stack.print();
stack.push(
0
);
stack.print();
stack.push(
1
);
13
14
15
16
17
Fig. 21.11
|
Stack manipulation program. (Part 1 of 2.)