-2

I'm trying to implement a stack using Arrays in Java. My Stack class consists of non static methods push, pop, peek and isempty. I want to test the stack implementation be instantiating the stack in a non static main method within a main class. When I try to do that I get an error "non-static method push(int) cannot be referenced from a static context" What am I doing wrong ?

Stack.java

public class Stack {

private int top;
private int[] storage;

Stack(int capacity){
    if (capacity <= 0){
        throw new IllegalArgumentException(
                "Stack's capacity must be positive");
    }
    storage = new int[capacity];
    top = -1;
}

void push(int value){
    if (top == storage.length)
        throw new EmptyStackException();
    top++;
    storage[top] = value;
}

int peek(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
}

int pop(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
  }
}

Main.java

public class Main {

public static void main(String[] args) {
    new Stack(5);
    Stack.push(5);
    System.out.println(Stack.pop());

 }
}
Batman
  • 39
  • 2
  • 8

1 Answers1

2

You've created a new instance, but didn't save that reference anywhere, so you lost it right after creating it. Instead, you should assign it to a variable and then apply the methods on it:

public static void main(String[] args) {
    Stack stack = new Stack(5);
    stack.push(5); // invoked on an instance "stack"
    System.out.println(stack.pop());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I made changes according to your comment. I'm getting an error **Exception in thread "main" java.lang.NoSuchMethodException: Stack.main([Ljava.lang.String;)** – Batman Jul 30 '16 at 20:47
  • Actually I think thats because I'm referencing a private variable. Thanks ! – Batman Jul 30 '16 at 20:50