Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

java - static vs non static

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...