我想知道什么时候使用静态方法?假设我有一个类,有几个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的main函数中吗?程序从那里开始执行,不需要创建对象。
考虑下面的例子:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
其他回答
在eclipse中,您可以启用一个警告,它可以帮助您检测潜在的静态方法。(在高亮线上方是另一个我忘记高亮的线)
java中的静态方法属于类(而不是类的实例)。它们不使用实例变量,通常从参数中获取输入,对其执行操作,然后返回一些结果。实例方法与对象相关联,并且,顾名思义,可以使用实例变量。
静态方法应该在类上调用,实例方法应该在类的实例上调用。但这在现实中意味着什么呢?下面是一个有用的例子:
car类可能有一个名为Accelerate()的实例方法。你只能加速一个汽车,如果汽车确实存在(已经构造),因此这将是一个实例方法。
car类也可能有一个名为GetCarCount()的计数方法。这将返回创建(或构造)的汽车总数。如果没有构造汽车,这个方法将返回0,但它仍然可以被调用,因此它必须是一个静态方法。
如果将静态关键字应用于任何方法,则称为静态方法。
静态方法属于类,而不是类的对象。 不需要创建类实例而调用的静态方法。 方法可以访问静态数据成员,并可以更改它的值。 静态方法可以通过类名。静态名来访问。示例:Student9.change(); 如果要使用类的非静态字段,则必须使用非静态方法。
//改变所有对象的公共属性的程序(静态字段)。
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111印度BBDIT 222美国BBDIT 333中国BBDIT
可以使用静态方法,如果
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;
}
};