class attributes declaration, order of the attributes' properties (final, private, static, type)
Solution 1
The language specification only says that modifiers must go before the type, thus int
comes last.
Modifiers include type parameters, annotations, access modifiers (private, protected, public), static
, final
, synchronized
, strictfp
, volatile
, transient
and they (from "what allows the compiler") can come in any order.
Some days ago I did a google search and static final
is much more often than final static
, so this helps ordering them :-)
I think in general this order of the modifiers is most common:
- Annotations
- type parameters
- access modifiers
static
final
-
transient
(only for fields) -
volatile
(only for variables) -
synchronized
(only for methods)
I never used strictfp
or native
, but I think I would put them around synchronized
.
Solution 2
You could take the default order as the order that appear in the Java Language Specification. http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#29882
Solution 3
When I care, I order according to checkstyle's ModifierOrder check [1] (citing from the linked page):
Checks that the order of modifiers conforms to the suggestions in the Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3. The correct order is:
- public
- protected
- private
- abstract
- static
- final
- transient
- volatile
- synchronized
- native
- strictfp
[1] http://checkstyle.sourceforge.net/config_modifier.html
Admin
Updated on June 24, 2022Comments
-
Admin almost 2 years
I'm trying to find documentation on what is the best way to order to properties of a class attribute, such as private/protected/public, final, static, type.
I'll post an example to see what I mean.
class A { public final static int FOO = 3; final public static int FOO = 3; }
Ok, I assume the attrbiute type (int, String, char) goes before the name of the attribute.
My real doubt is when I try to position static, final, and the v
-
Joachim Sauer about 13 yearsI, for one, disagree ;-) I much prefer
public static final
. -
Paŭlo Ebermann about 13 yearsI forgot transient and volatile (until I just used them in my project, and thus remembered this answer). And there is
native
too, for methods.