Is declaring a variable as private static varName;
any different from
declaring a variable private varName;
?
Yes, both are different. And the first one is called class variable
because it holds single value for that class
whereas the other one is called instance variable
because it can hold different value for different instances(Objects)
. The first one is created only once in jvm and other one is created once per instance i.e if you have 10 instances then you will have 10 different private varName;
in jvm.
Does declaring the variable as static
give it other special
properties?
Yes, static variables gets some different properties than normal instance variables. I've mentioned few already and let's see some here: class variables
(instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName
. And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects. Class variables can be used in static methods.
What is the use of a private static variable
in Java?
Logically, private static variable
is no different from public static variable
rather the first one gives you more control. IMO, you can literally replace public static variable
by private static variable
with help of public static
getter and setter methods.
One widely used area of private static variable
is in implementation of simple Singleton
pattern where you will have only single instance of that class in whole world. Here static
identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).
public class Singleton {
private static Singleton singletonInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return Singleton.singletonInstance;
}
}