I am told to declare and initialize my class constant. I didn't know what it was so I searched google, apparently everyone already knows what it is and nobody has asked on it. So what is a class constant? Is it just a value that doesn't change throughout the class?
2 Answers
JLS-8.3.1.1. static Fields says (in part)
A
staticfield, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
JLS-4.12.4. final Variables says (in part)
A constant variable is a
finalvariable of primitive type or typeStringthat is initialized with a constant expression (§15.28)
tl;dr
Putting that together, a class constant is a static final field.
Class variables are static; instance variables are not.
Final variables are constant.
So a class constant would be declared like this:
public class Foo {
// Class constant
public static final String DEFAULT_NAME = "Bar";
public static void main(String [] args) {
String name = Foo.DEFAULT_NAME;
}
}
It's the same for all instances of Foo.