我想知道什么时候使用静态方法?假设我有一个类,有几个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?
我很困惑!
当前回答
静态方法有两个主要目的:
用于不需要任何对象状态的实用程序或辅助方法。 由于不需要访问实例变量,具有静态 方法消除了调用方实例化对象的需要 只需要调用这个方法。 为了所有人共享的状态 类的实例,比如计数器。所有实例必须共享 相同的状态。仅仅使用该状态的方法应该是静态的 好。
其他回答
一个经验法则:问问自己“即使还没有构造对象,调用这个方法有意义吗?”如果是这样,它肯定是静态的。
在Car类中,你可能有一个方法:
double convertMpgToKpl(double mpg)
...这将是静态的,因为有人可能想知道35英里/加仑转换成什么,即使没有人制造过汽车。但是这个方法(设置一个特定Car的效率):
void setMileage(double mpg)
...不能是静态的,因为在构造任何Car之前调用该方法是不可想象的。
(顺便说一下,相反的情况并不总是正确的:你可能有时有一个方法涉及两个Car对象,但仍然希望它是静态的。例如:
Car theMoreEfficientOf(Car c1, Car c2)
虽然这可以转换为非静态版本,但有些人会认为,由于没有“特权”选择哪个Car更重要,所以不应该强迫调用者选择一个Car作为调用方法的对象。不过,这种情况在所有静态方法中只占相当小的一部分。
静态方法与实例不关联,因此它们不能访问类中的任何非静态字段。
如果方法不使用类的任何字段(或仅使用静态字段),则使用静态方法。
如果使用类的任何非静态字段,则必须使用非静态方法。
静态的: Obj.someMethod
当你想要提供对方法的类级访问时,使用static,即在没有类实例的情况下,方法应该是可调用的。
静态方法是一种不需要初始化任何对象就可以调用的方法。你注意到静态是用在Java的main函数中吗?程序从那里开始执行,不需要创建对象。
考虑下面的例子:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
可以使用静态方法,如果
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;
}
};