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

例子:

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

或:

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

我很困惑!


当前回答

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

其他回答

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;
    }
};

我想知道什么时候使用静态方法?

静态方法的一个常见用途是访问静态字段。 但是你可以有静态方法,而不需要引用静态变量。不引用静态变量的Helper方法可以在一些java类中找到,如java.lang. math 公共静态int min(int a, int b) { 返回(a <= b) ?A: b; } 另一个用例,我认为这些方法与同步方法相结合是在多线程环境中实现类级锁定。

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

如果你需要访问类的实例对象上的方法,你的方法应该是非静态的。

Oracle文档页提供了更多详细信息。

不是所有的实例和类变量和方法的组合都被允许:

实例方法可以直接访问实例变量和实例方法。 实例方法可以直接访问类变量和类方法。 类方法可以直接访问类变量和类方法。 类方法不能直接访问实例变量或实例方法——它们必须使用对象引用。而且,类方法不能使用this关键字,因为没有this的实例可以引用。

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

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