If a variable is declared as public static varName;
, then I can access it from anywhere as ClassName.varName
. I am also aware that static members a
Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances
Static variables have a single value for all instances of a class.
If you were to make something like:
public class Person
{
private static int numberOfEyes;
private String name;
}
and then you wanted to change your name, that is fine, my name stays the same. If, however you wanted to change it so that you had 17 eyes then everyone in the world would also have 17 eyes.
When in a static method you use a variable, the variable have to be static too as an example:
private static int a=0;
public static void testMethod() {
a=1;
}
I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class. e.g.:
public Class Company {
private static int numCompanies;
public static int getNumCompanies(){
return numCompanies;
}
}
Then you can sysout:
Company.getNumCompanies();
You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way". I have no idea if this is best practice or not, but it makes sense to me.
The private
keyword will allow the use for the variable access within the class and static
means we can access the variable in a static method.
You may need this cause a non-static reference variable cannot be accessible in a static method.
Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.
I would avoid thinking of static variables as being shared between "all instances" of the class - that suggests there has to be at least one instance for the state to be present. No - a static variable is associated with the type itself instead of any instances of the type.
So any time you want some state which is associated with the type rather than any particular instance, and you want to keep that state private (perhaps allowing controlled access via properties, for example) it makes sense to have a private static variable.
As an aside, I would strongly recommend that the only type of variables which you make public (or even non-private) are constants - static final variables of immutable types. Everything else should be private for the sake of separating API and implementation (amongst other things).