Final variables accessibility
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???
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.
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.
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.
精彩评论