Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a java class' final fields always be static?

Tags:

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.

like image 367
Karthick S Avatar asked Feb 16 '13 18:02

Karthick S


People also ask

Should fields be static Java?

"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.

When should I make a field static in Java?

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.

What is a static final field?

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".

Should static variables be final?

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.


1 Answers

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 } 
like image 106
JB Nizet Avatar answered Oct 06 '22 23:10

JB Nizet