Java Reference
In-Depth Information
user doesn't need to know how these methods are implemented. The Course class encapsu-
lates the internal implementation. This example uses an array to store students, but you could
use a different data structure to store students . The program that uses Course does not
need to change as long as the contract of the public methods remains unchanged.
10.9 Case Study: Designing a Class for Stacks
This section designs a class for modeling stacks.
Key
Point
Recall that a stack is a data structure that holds data in a last-in, first-out fashion, as shown in
Figure 10.10.
stack
Data1
Data2
Data3
Data3
Data2
Data1
Data2
Data1
Data1
Data3
Data2
Data1
Data2
Data1
Data1
F IGURE 10.10
A stack holds data in a last-in, first-out fashion.
Stacks have many applications. For example, the compiler uses a stack to process method
invocations. When a method is invoked, its parameters and local variables are pushed into a
stack. When a method calls another method, the new method's parameters and local variables
are pushed into the stack. When a method finishes its work and returns to its caller, its associ-
ated space is released from the stack.
You can define a class to model stacks. For simplicity, assume the stack holds the int val-
ues. So name the stack class StackOfIntegers . The UML diagram for the class is shown in
Figure 10.11.
VideoNote
The StackOfIntegers class
StackOfIntegers
-elements: int[]
-size: int
An array to store integers in the stack.
The number of integers in the stack.
+StackOfIntegers()
+StackOfIntegers(capacity: int)
+empty(): boolean
+peek(): int
Constructs an empty stack with a default capacity of 16.
Constructs an empty stack with a specified capacity.
Returns true if the stack is empty.
Returns the integer at the top of the stack without
removing it from the stack.
Stores an integer into the top of the stack.
Removes the integer at the top of the stack and returns it.
Returns the number of elements in the stack.
+push(value: int): void
+pop(): int
+getSize(): int
F IGURE 10.11
The StackOfIntegers class encapsulates the stack storage and provides the operations for manipulating
the stack.
Suppose that the class is available. The test program in Listing 10.7 uses the class to create
a stack (line 3), store ten integers 0 , 1 , 2 , . . . , and 9 (line 6), and displays them in reverse order
(line 9).
 
 
Search WWH ::




Custom Search