Using static to declare constants
suggest changeThe static keyword lets you access fields and methods without an instance of the class, so it can be used to declare constants for use in other classes. These fields are shared across every instance of the class. By convention, static final constants are written in ALL_CAPS and use underscores rather than camel case. For example:
static final E STATIC_VARIABLE_NAME;
As constants cannot change, static can also be used with the final modifier:
For example, to define the mathematical constant of pi:
public class MathUtilities {
static final double PI = 3.14159265358;
}
Which can be used in any class as a constant, for example:
public class MathCalculations {
//Calculates the circumference of a circle
public double calculateCircumference(double radius) {
return (2 * radius * MathUtilities.PI);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents