To see a practical application of the preceding discussion, let's develop one of the
archetypal examples of encapsulation: the stack. A stack stores data using first-in, last-out
ordering. That is, a stack is like a stack of plates on a table--the first plate put down on the
table is the last plate to be used. Stacks are controlled through two operations traditionally
called push and pop. To put an item on top of the stack, you will use push. To take an item off
the stack, you will use pop. As you will see, it is easy to encapsulate the entire stack mechanism.
Here is a class called Stack that implements a stack for integers:
// This class defines an integer stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
As you can see, the Stack class defines two data items and three methods. The stack of integers
is held by the array stck. This array is indexed by the variable tos, which always contains the
index of the top of the stack. The Stack( ) constructor initializes tos to ­1, which indicates an
empty stack. The method push( ) puts an item on the stack. To retrieve an item, call pop( ).
Since access to the stack is through push( ) and pop( ), the fact that the stack is held in an
array is actually not relevant to using the stack. For example, the stack could be held in a
more complicated data structure, such as a linked list, yet the interface defined by push( )
and pop( ) would remain the same.
The class TestStack, shown here, demonstrates the Stack class. It creates two integer stacks,
pushes some values onto each, and then pops them off.
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home