Java:何时使用静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2671496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: when to use static methods
提问by KP65
I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
我想知道什么时候使用静态方法?假设我有一个带有一些 getter 和 setter 的类,一两个方法,并且我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
e.g
例如
Obj x = new Obj();
x.someMethod
or
或者
Obj.someMethod
(is this the static way?)
(这是静态方式吗?)
I'm rather confused!
我比较糊涂!
采纳答案by not-just-yeti
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
一个经验法则:问问自己“即使尚未构造任何对象,调用此方法是否有意义?” 如果是这样,它肯定应该是静态的。
So in a class Car
you might have a method:
所以在一个类中Car
你可能有一个方法:
double convertMpgToKpl(double mpg)
...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car
. But this method (which sets the efficiency of one particular Car
):
...这将是静态的,因为人们可能想知道 35mpg 转换成什么,即使没有人曾经构建过Car
. 但是这种方法(它设置了一个特定的效率Car
):
void setMileage(double mpg)
...can't be static since it's inconceivable to call the method before any Car
has been constructed.
...不能是静态的,因为Car
在构造任何方法之前调用该方法是不可想象的。
(By the way, the converse isn't always true: you might sometimes have a method which involves two Car
objects, and still want it to be static. E.g.:
(顺便说一句,反过来并不总是正确的:您有时可能有一个涉及两个Car
对象的方法,但仍然希望它是静态的。例如:
Car theMoreEfficientOf( Car c1, Car c2 )
Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car
is more important, you shouldn't force a caller to choose one Car
as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)
虽然这可以转换为非静态版本,但有些人会争辩说,由于没有“特权”选择哪个Car
更重要,您不应该强迫调用者选择一个Car
作为您将调用的对象方法。不过,这种情况只占所有静态方法的一小部分。)
回答by Kevin Sylvestre
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
java中的静态方法属于类(不是它的实例)。它们不使用实例变量,通常会从参数中获取输入,对其执行操作,然后返回一些结果。实例方法与对象相关联,顾名思义,可以使用实例变量。
回答by duffymo
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
不,静态方法与实例无关;他们属于班级。静态方法是你的第二个例子;实例方法是第一个。
回答by Jamey
Use a static method when you want to be able to access the method without an instance of the class.
当您希望能够在没有类的实例的情况下访问方法时,请使用静态方法。
回答by Finbarr
Static:
Obj.someMethod
静止的:
Obj.someMethod
Use static
when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
使用static
时要提供一种方法,即其中的方法应该是可调用无类的实例类级别的访问。
回答by Carsten
Static methods are not associated with an instance, so they can not access any non-static fields in the class.
静态方法与实例无关,因此它们不能访问类中的任何非静态字段。
You would use a static method if the method does not use any fields (or only static fields) of a class.
如果方法不使用类的任何字段(或仅使用静态字段),您将使用静态方法。
If any non-static fields of a class are used you must use a non-static method.
如果使用类的任何非静态字段,则必须使用非静态方法。
回答by Alfred
After reading Misko's articles I believe that static methodsare bad from a testing point of view. You should have factoriesinstead(maybe using a dependency injection tool like Guice).
阅读 Misko 的文章后,我认为从测试的角度来看静态方法是不好的。你应该有工厂(也许使用像Guice这样的依赖注入工具)。
how do I ensure that I only have one of something
我如何确保我只有一个东西
only have one of something The problem of “how do I ensure that I only have one of something” is nicely sidestepped. You instantiate only a single ApplicationFactory in your main, and as a result, you only instantiate a single instance of all of your singletons.
只有一个东西“我如何确保我只有一个东西”的问题被很好地回避了。您只在 main 中实例化了一个 ApplicationFactory,因此,您只实例化了所有单例的一个实例。
The basic issue with static methods is they are procedural code
静态方法的基本问题是它们是过程代码
The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I wire the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is nothing to "wire" since there are no objects, the code and data are separate.
静态方法的基本问题是它们是过程代码。我不知道如何对程序代码进行单元测试。单元测试假设我可以单独实例化我的应用程序的一部分。在实例化过程中,我使用模拟/友好来连接依赖项,它们替换了真正的依赖项。由于没有对象,代码和数据是分开的,因此程序编程没有什么可以“连接”的。
回答by Vaishak Suresh
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
不需要在对象上调用静态方法,这就是您使用它的时候。示例:您的 Main() 是静态的,您没有创建对象来调用它。
回答by Mohd
Define static methods in the following scenarios only:
仅在以下场景中定义静态方法:
- If you are writing utility classes and they are not supposed to be changed.
- If the method is not using any instance variable.
- If any operation is not dependent on instance creation.
- If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
- If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
- 如果您正在编写实用程序类并且不应更改它们。
- 如果该方法未使用任何实例变量。
- 如果任何操作不依赖于实例创建。
- 如果有一些代码可以很容易地被所有实例方法共享,则将该代码提取到静态方法中。
- 如果您确定该方法的定义永远不会被更改或覆盖。作为静态方法不能被覆盖。
回答by Manju Yadav
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName()
or classInstanceName.methodName()
, i.e. static methods and variables can be accessed using class name as well as instances of the class.
静态方法和变量是 Java 中“全局”函数和变量的受控版本。其中方法可以作为classname.methodName()
或访问classInstanceName.methodName()
,即可以使用类名以及类的实例访问静态方法和变量。
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
类不能被声明为静态(因为它没有意义。如果一个类被声明为公共,它可以从任何地方访问),内部类可以被声明为静态。