declaringn a variable in java class (private,static,final)
This question already has an answer here:
private
means it can be accessed only by instances of class foo
.
public
means it can be accessed from any object owning a reference to an instance of Class foo
.
static
means it belongs to the class and thus, it's shared by all foo
instances.
final
means it can't change its initial value.
final
properties can't be modified once initialized. static
properties can be modified, but remember that the new value is shared by all instances. private
properties can be modified only by a foo
instance itself.
This means that a static final
property that: can't be modified; is shared by all instances.
public
attributes can be accessed from any class.
private
attributes can be accessed just in the class where it's declared. (This is why we need to include getters and setters for example in the other classes to retrieve private vars)
final
attributes cannot be modified and set to a different value.
static
attributes are accessed in the class itself and in its instances.
private static final int a; // accessed only / inside only
private static int b; // accessed and modified / inside only
private final int c; // accessed only / inside only
private int d; // accessed and modified / inside only
public static final int e; // accessed only / inside and outside
public static int f; // accessed and modified / inside and outside
public final int g; // accessed only / inside and outside
public int h; // accessed and modified / inside and outside
As you can see:
static
has no effect here whatsoever final
reduces accessed and modified
to accessed only
private
/ public
determines inside only
/ inside and outside