Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private static final vs private final

Tags:

java

memory

This question has been asked here. As per the answer :

private final int NUMBER = 10;

If it cannot change, there is no point having one copy per instance.

My doubt is what if instance of the class is created, say once a day and it lasts around a few seconds. Is it good idea to keep the int(in some case object) in memory?

Assuming, there can be many (20-30) such objects.

like image 606
codingenious Avatar asked Mar 24 '14 11:03

codingenious


2 Answers

How you store the information depends very much on what it is intended to be used for.

There are a few approaches you might take:

private static final

This is a good choice if the value will never be modified during the lifetime of the application. It means, when you're creating your multiple instances, you are only actually storing this particular variable ONCE.

private final

This is meant for those times when the value might take on different values for different instances of your object, but any specific instance will not have it's value modified throughout the object's life time.

If you're looking at something which might take on different values over a range of time, then this might be of interest to you.

public static int GetNumber(){...}

Another approach you might consider is to have a static method return the value you are after. This makes it easy to deal with changes in the value, but you also need to consider the effect of such a change throughout the lifetime of any given instance.

Hope that helps...

like image 79
Martin Milan Avatar answered Oct 23 '22 04:10

Martin Milan


Regarding private final int number, your claim that

If it cannot change, there is no point having one copy per instance

is absolutely wrong. Consider this code, typical of an immutable class:

private final int number;

public MyClass(int number) {
    this.number = number;
}

There are many instances of this pattern in the JDK, and in production code classes around the globe.


To answer your question about performance, I doubt you could measure the difference between using static vs instance constants.

like image 44
Bohemian Avatar answered Oct 23 '22 02:10

Bohemian