Java 静态与非静态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20592520/
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
static vs non static
提问by Batty
Until few weeks back, I thought I understand when to make fields and methods static
or non-static
. For example, when a field (say object of another class) is unique for any number of objects for the class, it should be made static
.
直到几周前,我以为我了解何时创建字段和方法static
或non-static
. 例如,当一个字段(比如另一个类的对象)对于该类的任意数量的对象是唯一的时,它应该被制作static
。
But then I read about JVM garbage collection a few weeks back.
但是几周前我读到了 JVM 垃圾收集。
I understand that static
fields are never garbage collected and remain in memory all along, unless the class loader itself is garbage collected.
我知道static
字段永远不会被垃圾收集并一直保留在内存中,除非类加载器本身被垃圾收集。
But if I don't make that field static
, at least it will be garbage collected.
但是如果我不做那个字段static
,至少它会被垃圾收集。
So, it seems there is a very thin linebetween making fields/methods static or not.
因此,似乎在使字段/方法静态与否之间存在非常细小的界限。
Can anybody please explain to me this thin linein deciding, so that my application is way more efficient.
任何人都可以在决定时向我解释这条细线,以便我的应用程序更有效率。
采纳答案by anubhava
It might be thin but there is very clear distinction. You declare a field as static when it is not at all related to any instance of a class.
它可能很薄,但有非常明显的区别。当一个字段与类的任何实例完全无关时,您将其声明为静态字段。
A simple usecase of static field is declaring constants using final
keyword, e.g.:
静态字段的一个简单用例是使用final
关键字声明常量,例如:
public static final int MAX_ALLOWED = 10;
Same is the case with methods also. You declare a method as static when it is not dependent on instance of a class OR the state of the class. That's the reason a static method cannot use instance members of a class.
方法也是如此。当一个方法不依赖于类的实例或类的状态时,您将其声明为静态方法。这就是静态方法不能使用类的实例成员的原因。
回答by fastcodejava
Fields are not made static
over garbage collection. That is whole new area to consider. If the memory is huge for your static
field, yeah you should make it non-static
.
字段不是static
通过垃圾收集生成的。这是需要考虑的全新领域。如果你的static
领域内存很大,是的,你应该做到non-static
。
回答by Amir Pashazadeh
These are not mandatory rules, but it is better to follow them:
这些不是强制性规则,但最好遵循它们:
When to use static fields:
何时使用静态字段:
- ConstantsBest usage of static fields are constants, which shall be
final
too. - ThreadLocalsMost of the time you define thread-local variables static, otherwise you usually lose the reference to them. But don't forget to release their contents when there is no more use (or you will encounter memory leaks). Most of the time these variables are finaltoo.
- And very rare cases when you shall keep a reference to a (semantically) singleton object which could be accessed from many places. (For example a reference to Hibernate
SessionFactory
in HibernateUtils).
- 常量静态字段的最佳用法是常量,这也应该是常量
final
。 - ThreadLocals大多数时候你定义线程局部变量是静态的,否则你通常会失去对它们的引用。但是不要忘记在不再使用时释放它们的内容(否则你会遇到内存泄漏)。大多数情况下,这些变量也是最终的。
- 在非常罕见的情况下,您应该保留对可以从许多地方访问的(语义上的)单例对象的引用。(例如
SessionFactory
在 HibernateUtils 中对 Hibernate 的引用)。
Remember that, static fields shall usually be immutable during runtime of your application (they are sometimes modified during start-up and tear-down of the application).
请记住,静态字段在应用程序运行时通常是不可变的(它们有时在应用程序的启动和拆卸期间会被修改)。
When to use static methods:
何时使用静态方法:
- Helper utility methodsthat's the normal case, when a method does not depend on state of its containing object. These methods can be useful, and can be accessed without instantiating any object.
- Factory methodsFactory methods are another good example of where to use static methods.
- Private methods which are not depend on objects state, when a private method just have no dependency on object's state, it is much better to define it
static
to gain a little performance. - void main(String[])method shall be static too.
- 当一个方法不依赖于其包含对象的状态时,这是正常情况下的辅助实用程序方法。这些方法很有用,并且无需实例化任何对象即可访问。
- 工厂方法工厂方法是另一个使用静态方法的好例子。
- 不依赖于对象状态的私有方法,当私有方法只是不依赖于对象的状态时,最好定义它
static
以获得一点性能。 - void main(String[])方法也应该是静态的。
回答by Eden
Static fields is a conceptyou should really think carefully about before using it as a method to increase the efficiency of your application.
在将静态字段用作提高应用程序效率的方法之前,您应该仔细考虑静态字段的概念。
As you know when static modifier is included in a field , no instance of the class is required for it to be used. And as a result it has a the same value for the entire application. On one hand it can lead to many bugs in multi-threaded read/write environment if you don't properly serialize the access, on the other hand it is good thing if you trying to create singleton pattern(A field with a value that do not change during the life time of the application and therefor do not need to be GC)
如您所知,当字段中包含 static 修饰符时,不需要使用该类的实例。因此,它对整个应用程序具有相同的值。一方面,如果您没有正确地序列化访问,它可能会导致多线程读/写环境中的许多错误,另一方面,如果您尝试创建 单例模式(具有值的字段)在应用程序的生命周期内不会改变,因此不需要 GC)
By and large you should avoid read/write static fields, it will introduce more bugs into your application. Having the same value across many instances of the same class is not considered a good use case for static field in OO design. Not because it is less or more efficient but because it breaks the concept of encapsulation.
总的来说,您应该避免读/写静态字段,它会在您的应用程序中引入更多错误。对于 OO 设计中的静态字段,在同一类的许多实例中具有相同的值不被认为是一个好的用例。不是因为它的效率较低或较高,而是因为它打破了封装的概念。