Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'public static final' or 'private static final' with getter?

In Java, it's taught that variables should be kept private to enable better encapsulation, but what about static constants? This:

public static final int FOO = 5; 

Would be equivalent in result to this:

private static final int FOO = 5; ... public static getFoo() { return FOO; } 

But which is better practice?

like image 299
Chris Cummins Avatar asked Apr 06 '12 18:04

Chris Cummins


People also ask

Should static final variables be public?

Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables.

Should getters and setters be final?

It makes sense to make a getter final if the POJO aimed to be immutable. final modifier will disable sub classes to override that method. You should only use it if you want this design, but it depends.

Why would it be OK to declare a final or static final variable as public?

public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified.

Why have a private static final?

private static final will be considered as constant and the constant can be accessed within this class only. Since, the keyword static included, the value will be constant for all the objects of the class. private final variable value will be like constant per object. You can refer the java.


1 Answers

There's one reason to not use a constant directly in your code.

Assume FOO may change later on (but still stay constant), say to public static final int FOO = 10;. Shouldn't break anything as long as nobody's stupid enough to hardcode the value directly right?

No. The Java compiler will inline constants such as Foo above into the calling code, i.e. someFunc(FooClass.FOO); becomes someFunc(5);. Now if you recompile your library but not the calling code you can end up in surprising situations. That's avoided if you use a function - the JIT will still optimize it just fine, so no real performance hit there.

like image 172
Voo Avatar answered Sep 29 '22 14:09

Voo