我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
当前回答
实际上,我们在类中使用静态属性和方法,当我们想要使用程序的某些部分时,它们应该一直存在,直到程序运行为止。我们知道,要操作静态属性,我们需要静态方法,因为它们不是实例变量的一部分。如果没有静态方法,操作静态属性是非常耗时的。
其他回答
静态方法和变量是Java中“全局”函数和变量的受控版本。其中方法可以作为classname.methodName()或classInstanceName.methodName()访问,即静态方法和变量可以使用类名以及类的实例访问。
类不能被声明为静态的(因为它没有意义。如果一个类被声明为public,它可以从任何地方访问),内部类可以被声明为static。
静态方法与实例不关联,因此它们不能访问类中的任何非静态字段。
如果方法不使用类的任何字段(或仅使用静态字段),则使用静态方法。
如果使用类的任何非静态字段,则必须使用非静态方法。
使用静态方法有一些合理的理由:
Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right? Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter. Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet. Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).
如果你想创建一个单例,你还必须创建一个静态方法,但是…不喜欢。我的意思是,三思而后行。
更重要的是,为什么不想创建静态方法?基本上,多态被抛在了脑后。你不能重写这个方法,也不能在接口中声明它(在java 8之前)。这给你的设计带来了很大的灵活性。此外,如果您需要状态,如果您不小心,您将以大量并发错误和/或瓶颈告终。
可以使用静态方法,如果
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;
}
};
只在以下场景下定义静态方法:
如果您正在编写实用程序类,并且它们不应该被更改。 如果该方法没有使用任何实例变量。 如果任何操作不依赖于实例创建。 如果有一些代码可以很容易地被所有实例方法共享,那么将这些代码提取到静态方法中。 如果您确定方法的定义永远不会被更改或重写。因为静态方法不能被覆盖。