Is there any use for a private constant, that is not static?
Is there any reason to have a private constant, that is not static? Are there any situations that you would need a non-static private const? Would it make sense if constants where static by default?
I use ActionScript3 and some Java, but I开发者_开发百科 think this is a broader OOP question.
I don't know if this counts, but in Java you need to make local variables final to be able to use them in inner classes (because Java has no real closures, and instead makes copies of the captured scope, which must henceforth be immutable):
void test(){
final long startTime = System.currentTimeMillis(); // needs to be final
new Runnable(){
System.out.println(startTime);
}.run();
}
Also, you can make fields and variables final in order to protect yourself from accidentally re-assigning them (and the compiler and runtime may also use this information for performance optimizations).
Of course, both of these examples are not really about constants in the mathematical sense (final variables in Java can be assigned to computed expressions depending on variable input).
Another reason other than the accessing the variable in the anonymous class (like Thilo said) is if you want an object that you can't change the assignment of, but it maintains some state of the current object, and thus you can't share it among multiple instances of the class.
C# has this concept of readonly fields i.e. fields that can only be assigned in the constructor and cannot be changed in any other method. They are like constants for a specific instance of a class (outside its constructor) rather than for the class itself.
精彩评论