mahmood mahmood - 1 month ago 9
Java Question

declaringn a variable in java class (private,static,final)

There are many discussions about

static
and
final
variables in Java. However, 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?

Answer

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.

Comments