-2
Stack newStack = new Stack();
newStack.push(0);

OR

Stack.push(0);

Note: Here Stack is a user defined class to implement concept of stack manually in java and not the predefined one.

  • Does this answer your question? [Is using a lot of static methods a bad thing?](https://stackoverflow.com/questions/752758/is-using-a-lot-of-static-methods-a-bad-thing) If not really, then search for more. – Ole V.V. May 12 '20 at 04:20
  • On the other hand, if the design of `Stack` is given and `push` *is* a static method, then `Stack.push(0)` is clearly preferred as clearest and concisest. – Ole V.V. May 12 '20 at 04:22

2 Answers2

1

This allows having multiple stacks for different purposes.

Stack newStack = new Stack();
newStack.push(0);

We can have only one stack when using this.

Stack.push(0);

I prefer the first one as it allows initializing multiple stacks at the same time which the second way can't do.

Nandu Raj
  • 2,072
  • 9
  • 20
0

In the first example, push is a non-static method of the Stack class. In order to use the push method, you have to create an instance of the Stack class.

Stack newStack = new Stack();
newStack.push(0);

The equivalent code with an anonymous instance would be:

new Stack().push(0);

which would be kind of useless in this case, since you're eventually going to want to pop the stack you created.

In the second example, push is a static method of the Stack class.

Stack.push(0);

Nandu Raj is correct in his answer in that you can only have one Stack in your application, rather than more than one with the non-static push method.

Creating and using non-static methods is generally a better programming practice, although there are cases, like the Java Math class, where static methods work better.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111