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

10,025

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:

  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.

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:

  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

Share:
10,025
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    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
    Joachim Sauer about 13 years
    I, for one, disagree ;-) I much prefer public static final.
  • Paŭlo Ebermann
    Paŭlo Ebermann about 13 years
    I forgot transient and volatile (until I just used them in my project, and thus remembered this answer). And there is native too, for methods.