I could not find any references online about this. But just wanted to know if final fields in a class should always be static
or is it just a convention. Based on my understanding of their uses, I feel that it is more of a logical thing to do than something that is imposed by the language.
"A final field should also be declared static if it is initialised in its declaration to a value." Who ever wrote that should differ between mutable and immutable types. They aren't the same.
The use of a static field means that each object does not need to know about the other objects to get a unique id. This could be useful if you wanted to know the order in which the Item objects were created.
A final field cannot have its value changed. A final field must have an initial value assigned to it, and once set, the value cannot be changed again. A final field is often also declared static . A field declared static and final is also called a "constant".
Static variables are stored in the static memory, mostly declared as final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.
Of course not. They must be static if they belong to the class, and not be static if they belong to the instance of the class:
public class ImmutablePerson { private static final int MAX_LAST_NAME_LENGTH = 255; // belongs to the type private final String firstName; // belongs to the instance private final String lastName; // belongs to the instance public ImmutablePerson(String firstName, String lastName) { if (lastName.length() > MAX_LAST_NAME_LENGTH) { throw new IllegalArgumentException("last name too large"); } this.firstName = firstName; this.lastName = lastName; } // getters omitted for brevity }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With