静态与非静态 [英] static vs non static

查看:113
本文介绍了静态与非静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到几周前,我想我理解何时使字段和方法 static 非静态。例如,当一个字段(比如另一个类的对象)对于该类的任何数量的对象都是唯一的时,它应该被设为 static



但是后来我在几周前阅读了有关JVM垃圾回收的内容。



据我所知,<$ c $除非类加载器本身被垃圾回收,否则c> static 字段永远不会被垃圾收集并保留在内存中。



但是如果我不不要让这个字段 static ,至少它会被垃圾收集。

所以,看起来有一个 非常细线 在使字段/方法静态或不是。



任何人都可以向我解释 thin line 来决定,这样我的应用程序的效率就会更高。

它可能很薄,但有非常明显的区别。如果一个字段与类的任何实例都没有关系,则声明该字段为静态。



静态字段的一个简单用例是使用 final 关键字,例如:

  public static final int MAX_ALLOWED = 10; 

方法也是如此。当它不依赖于类的实例或类的状态时,将方法声明为静态方法。这就是静态方法不能使用类的实例成员的原因。


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.

But then I read about JVM garbage collection a few weeks back.

I understand that static fields are never garbage collected and remain in memory all along, unless the class loader itself is garbage collected.

But if I don't make that field static, at least it will be garbage collected.

So, it seems there is a very thin line between making fields/methods static or not.

Can anybody please explain to me this thin line in deciding, so that my application is way more efficient.

解决方案

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.:

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.

这篇关于静态与非静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆