tags:

views:

81

answers:

3

Why can't Final variables be accessed in a static variables. At the compile time they are simply substituted directly substituted with their values so, they should be allowed to use even in static methods

why is this restriction???

+2  A: 

Not all final variables are compile time constants. Only static final variables can be substituted by compiler as compile-time constants. final modifier in certain cases is only used to ensure const-correctness.

And static methods cannot access non-static variables as those variables can have different values for different instances of the same class.

missingfaktor
+1  A: 

If you're asking why a static method cannot access a final instance variable (on the [incorrect] assumption that final member variables are always set to literal or constant values in the code), its because different instances of a class can have different values for the same final instance variable (which can be set, for example, via the constructor). A static method has no knowledge of any particular instance of the class, and could only access static final variables.

danben
+3  A: 

static = in the class.

final = doesn't change it's value (but it is of each instance if it's not static).

By examply you can do:

public class Weird
{
private static long number = System.getTimeInMilis();
private final long created = System.getTimeInMilis();
}

Each time you create a Weird object it will contain a different value for created.

But the value of Weird.number will be the time when the class was loaded.

helios
A more real example: you can create a "private final list = new ArrayList<...>" and you will not change the reference to the list but the list can add objects when you want.
helios
...does not change the value *after assignment*. This is compiler enforced, not jvm enforced
Thorbjørn Ravn Andersen