我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?

例子:

Obj x = new Obj();
x.someMethod();

或:

Obj.someMethod(); // Is this the static way?

我很困惑!


当前回答

实际上,我们在类中使用静态属性和方法,当我们想要使用程序的某些部分时,它们应该一直存在,直到程序运行为止。我们知道,要操作静态属性,我们需要静态方法,因为它们不是实例变量的一部分。如果没有静态方法,操作静态属性是非常耗时的。

其他回答

不,静态方法不与实例关联;他们属于这个阶层。静态方法是第二个例子;实例方法是第一个。

在eclipse中,您可以启用一个警告,它可以帮助您检测潜在的静态方法。(在高亮线上方是另一个我忘记高亮的线)

我发现了一个很好的描述,当使用静态方法:

没有硬性的、写得很好的规则来决定什么时候使一个方法静态或非静态,但是有一些基于经验的观察,这不仅有助于使一个方法静态,而且还教会了什么时候在Java中使用静态方法。你应该考虑在Java中让一个方法是静态的:

If a method doesn't modify state of object, or not using any instance variables. You want to call method without creating instance of that class. A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument. Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not. If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.

来源在这里

静态方法与实例不关联,因此它们不能访问类中的任何非静态字段。

如果方法不使用类的任何字段(或仅使用静态字段),则使用静态方法。

如果使用类的任何非静态字段,则必须使用非静态方法。

实际上,我们在类中使用静态属性和方法,当我们想要使用程序的某些部分时,它们应该一直存在,直到程序运行为止。我们知道,要操作静态属性,我们需要静态方法,因为它们不是实例变量的一部分。如果没有静态方法,操作静态属性是非常耗时的。