There are many discussions about static
and final
variables in Java.
I really want to know the differences between the following declarations. Seems to be confusing
public class foo() {
private static final int a;
private static int b;
private final int c;
private int d;
public static final int e;
public static int f;
public final int g;
public int h;
}
Which one can be modified/accessed inside/outside of the class?
P.S: The question in In Java, difference between default, public, protected, and private is a larger scope. Mine is focusing on some confusing points!
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.