[英]Which one of the below is a better programming practice in java to call methods present in a user defined class?
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.注意:这里的 Stack 是用户定义的 class 以在 java 中手动实现堆栈的概念,而不是预定义的。
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.我更喜欢第一种方法,因为它允许同时初始化多个堆栈,而第二种方法无法做到。
In the first example, push
is a non-static method of the Stack
class.在第一个示例中,
push
是Stack
class 的非静态方法。 In order to use the push
method, you have to create an instance of the Stack
class.为了使用
push
方法,您必须创建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.在这种情况下这将是无用的,因为您最终会想要
pop
您创建的堆栈。
In the second example, push
is a static method of the Stack
class.在第二个示例中,
push
是Stack
class 的 static 方法。
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. Nandu Raj 的回答是正确的,因为您的应用程序中只能有一个
Stack
,而不是使用非静态push
方法的多个 Stack。
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.创建和使用非静态方法通常是一种更好的编程实践,尽管在某些情况下,例如 Java
Math
class,其中 static 方法效果更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.