Java modifiers syntax and format

后端 未结 5 766
梦谈多话
梦谈多话 2020-11-28 14:09

I find myself getting confused as to the order of access and non access modifiers. For example

abstract void go()  
abstract public void go()  
public final          


        
相关标签:
5条回答
  • 2020-11-28 14:17

    From the official grammar of the Java Programming Language (simplified):

    Modifier:
      Annotation | public | protected | private
      static | abstract | final | native | synchronized
      transient | volatile | strictfp
    
    ClassOrInterfaceDeclaration:
            {Modifier} (ClassDeclaration | InterfaceDeclaration)
    
    ClassBodyDeclaration:
            {Modifier} MethodOrFieldDecl
    
    MethodOrFieldDecl:
            Type Identifier MethodOrFieldRest
    

    So, for classes and interfaces, the modifiers must always appear before the class keyword, and in any order. E.g., final public class is valid, but class final is not. For methods and fields, it is the same, but the modifiers must appear before the type.

    0 讨论(0)
  • 2020-11-28 14:20

    See http://checkstyle.sourceforge.net/config_modifier.html.

    The correct (or rather, conventional) order is :

    1. public
    2. protected
    3. private
    4. abstract
    5. static
    6. final
    7. transient
    8. volatile
    9. synchronized
    10. native
    11. strictfp

    This order should come naturally to your mind after some days programming in Java.

    0 讨论(0)
  • 2020-11-28 14:21

    Yes, there's the Java Language Specification, which explains all that is valid syntax in the language and there is also the coding conventions used by Oracle/Sun, which is a bit old but still explains a lot of stuff.

    0 讨论(0)
  • 2020-11-28 14:33

    Just as in the English language, adjectives (modifiers such as public, static, volatile, etc) precede the noun they describe (class, interface, or any type such as int or String). The order of the modifiers doesn't matter to the language, but by reading code you'll quickly find which feel more natural.

    0 讨论(0)
  • 2020-11-28 14:36

    Modifiers go before the class or a type. According to the Java Language Specification, order between modifiers does not matter.

    0 讨论(0)
提交回复
热议问题