// Supplementary to "Software Design ...", John A Robinson, Newnes, 2004, import java.io.*; class stack // Not a public class: only used in this file (for this example). { // First come the private data items int stack_length; // To allow the caller to set max length int stack_base[]; // Stack array int stack_pointer; public stack(int size) // This is the constructor { stack_base = new int[stack_length = size]; stack_pointer = 0; }; // No destructor necessary public int push(int value) { if (stack_pointer == stack_length) return(-1); // Stack full stack_base[stack_pointer++] = value; return(0); } public int pop(int value[]) // Primitive objects can't be passed by reference in Java, so we // have to create an array (or an object) in the caller and pass // it (because non-primitive objects are always passed by reference). // If writing from scratch rather than translating from C++, we // might instead maintain a stack of stack_objects rather than of // ints. { if (stack_pointer == 0) return(-1); // Stack empty value[0] = stack_base[--stack_pointer]; return(0); } }; public class stacktest { public static void main(String args[]) { stack my_stack = new stack(10); // Note initialization, not // stack my_stack(10); // Saying that I won't be putting more // than 10 items on the stack. my_stack.push(345); my_stack.push(678); // Here is the array we declare so as to pass by reference. int test[] = new int[1]; my_stack.pop(test); System.out.println(test[0] + " was just popped off the stack"); } }