Private Final Static Attribute VS Private Final Attribute

Private Final vs Final Private

The Java Language Specification, section 8.3.1. Field Modifiers, says:

FieldModifier:
(one of)
Annotation public protected private
static final transient volatile

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.

Which means that private final is the preferred style, but it's exactly the same as final private.

declaringn a variable in java class (private,static,final)

private means it can be accessed only by instances of class foo.

public means it can be accessed from any object owning a reference to an instance of Class foo.

static means it belongs to the class and thus, it's shared by all foo instances.

final means it can't change its initial value.

final properties can't be modified once initialized. static properties can be modified, but remember that the new value is shared by all instances. private properties can be modified only by a foo instance itself.

This means that a static final property that: can't be modified; is shared by all instances.

Should a private final field be static too?

If every instance of your class should have the same immutable value for foo, then you should make foo final and static. If each instance of your class can have a different (but still immutable) value for foo, then the value should just be final.

However, if every instance of your class should have the same immutable value for foo, then it is a really a constant. By convention, that is typically coded as follows:

private static final int FOO = ...

Note the caps to denote a constant...

private static final fields

Once a variable is declared final, its value cannot be changed later. In the code sample you provided, a constant is declared for defining the age of a student for a particular activity. It might mean that there will be a condition where for certain activity, the age of the student will be compared with this constant. If the age of student is greater than 18, then only he will be allowed to proceed or not.

Is it okay to declare a Random object as a private static final attribute?

"Better" always depends on your exact requirements.

The things to consider:

  • do you want your code to be testable (the above is only to a certain degree)
  • do you want your code to work in a multi threaded environment, and should the different threads see the same random numbers

In other words, the distinct non-answer: you have to understand the contract that your code will be used for. Then you can decide what is appropriate.

The above is probably okay on a "throw away after single exercise" level, but not more.



Related Topics



Leave a reply



Submit