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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With