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

例子:

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

或:

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

我很困惑!


当前回答

当您希望能够在没有类实例的情况下访问方法时,请使用静态方法。

其他回答

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

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

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

你应该在任何时候使用静态方法,

方法中的代码不依赖于实例创建,而是依赖于实例创建 不使用任何实例变量。 特定的一段代码将由所有实例方法共享。 不应更改或重写方法的定义。 您正在编写不应该更改的实用程序类。

https://www.tutorialspoint.com/When-to-use-static-methods-in-Java

静态的: Obj.someMethod

当你想要提供对方法的类级访问时,使用static,即在没有类实例的情况下,方法应该是可调用的。

java中的静态方法属于类(而不是类的实例)。它们不使用实例变量,通常从参数中获取输入,对其执行操作,然后返回一些结果。实例方法与对象相关联,并且,顾名思义,可以使用实例变量。

可以使用静态方法,如果

One does not want to perform an action on an instance (utility methods) As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below 1. new ABCClass(double farenheit).convertFarenheitToCelcium() 2. ABCClass.convertFarenheitToCelcium(double farenheit) the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below: Math.random() Math.sqrt(double) Math.min(int, int) StringUtils.isEmpty(String) StringUtils.isBlank(String) One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.

注意: 很少有人反对静态方法的可测试性,但是静态方法也可以被测试!使用jMockit,可以模拟静态方法。可测试性。在下面的例子:

new MockUp<ClassName>() {
    @Mock
    public int doSomething(Input input1, Input input2){
        return returnValue;
    }
};