Reputation: 10707
Why would you declare a static final
variable as private
for an immutable type?
Could it possibly do any harm to declare them public
on any case?
Upvotes: 3
Views: 1074
Reputation: 59
public class GUICommon {
private static final ExecutorService executorServices = Executors.newWorkStealingPool();
public static void useExecutors(Runnable run)
{
executorServices.execute(run);
}
}
I used it on this way.
Upvotes: 0
Reputation: 17595
There are serveral reasons...
Privacy
Keep implementation details hidden from the clients, for example constants for internal use only and with no use for clients
Security
Protect your code from maliscious client codes for example:
static class A
{
public final static List<String> list = buildList();
public static List<String> buildList()
{
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList("A", "B", "C"));
return list;
}
}
static class B
{
public static void main(String[] args)
{
A.list.clear();
System.out.println(A.list);
}
}
You dont want any one to manipulate you internal data.
Upvotes: 3
Reputation: 4168
It's just best OOP practice to keep variables within the proper scope. An example would be a global static final integer for performing a number of calculations within the class. Having it exposed (public) not only could cause problems, but confusion as well.
Say you had a class where you needed to know the value of pi:
public class MyClass {
private static final double PI = 3.14159;
//functions performing calculations with value of PI
}
The value of pi is only needed within MyClass
, so leaving it to be exposed makes no sense - all calculations with the variable are done within MyClass
. If you need it again to perform a calculation, it should be done within the class holding the value to keep your code organized.
Upvotes: 0
Reputation: 4091
So that nobody can access it from outside and rely on that value, giving you the freedom to change it without risk of side-effect (at least outside of the class where it's declared).
Upvotes: 3