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, Strin开发者_运维百科g, char) goes before the name of the attribute.
My real doubt is when I try to position static, final, and the v
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
.
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
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
Answered your own question:
private/protected/public, static, final, type
The order of field (class, method) modifiers doesn't matter. They're just flags, when we look at the method signature.
So if you want to use a fixed order, it is only for readability. And your code looks better, if you always use the same order in your compilation units.
But again, the order has no effect on the byte code. Forget about micro optimization ;)
精彩评论