|
|
public interface Stack { public void push( int x ); public int pop ( ); } |
public class ArrayStack { /* ================================================== Variables to represent a stack ================================================== */ public int[] item; public int stackTop; /* ================================================== Constructor: create an array of given size ================================================== */ public ArrayStack( int size ) { item = new int[size]; // Make an array of size as stack storage stackTop = 0; } /* ================================================================= The push() method ================================================================= */ public void push( int x ) { item[stackTop] = x; // Store x in next slot stackTop++; // Advance one slot location } /* ================================================================= The pop() method ================================================================= */ public int pop ( ) { int returnItem; returnItem = item[ stackTop-1 ]; // Get last stored item stackTop--; // Back up one slot location return returnItem; } } |
|
|
|
Note: these rules are same as the ones for base/derived classes !
|
|
|
|
|
Stack s = new ArrayStack( ... ); s.push( 4 ); <--- will call push() in ArrayStack (version 1) |
Note:
|
|
|
|
|
public class testProg1 { public static void main( String[] args ) { int x; Stack s; s = new ArrayStack( 10 ); // We will use methods from the ArrayStack class x = 4; s.push(x); System.out.println("push(" + x + ");"); x = 7; s.push(x); System.out.println("push(" + x + ");"); x = 8; s.push(x); System.out.println("push(" + x + ");"); x = 9; s.push(x); System.out.println("push(" + x + ");"); x = s.pop(); System.out.println("pop() ---> " + x ); x = s.pop(); System.out.println("pop() ---> " + x ); x = s.pop(); System.out.println("pop() ---> " + x ); x = s.pop(); System.out.println("pop() ---> " + x ); } } |
Key to understand the behavior of the above program:
|
How to run the program:
|