开发者

class attributes declaration, order of the attributes' properties (final, private, static, type)

开发者 https://www.devze.com 2023-02-11 16:04 出处:网络
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'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:

  1. Annotations
  2. type parameters
  3. access modifiers
  4. static
  5. final
  6. transient (only for fields)
  7. volatile (only for variables)
  8. 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:

  1. public
  2. protected
  3. private
  4. abstract
  5. static
  6. final
  7. transient
  8. volatile
  9. synchronized
  10. native
  11. 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 ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消