Java modifiers syntax and format

后端 未结 5 774
梦谈多话
梦谈多话 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.

提交回复
热议问题