开发者

Java modifiers syntax and format

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 void go()  
vo开发者_JS百科id final go()  

final class Test{}  
class final Test{}  
final abstract class Test{}  
abstract final Test{}  

I never know what the correct order is and sometimes I get it wrong because there are so many possible combinations. Is there a definite guide as to which should come before the other?

Is there any description of the format and order in which they are to appear in the code? I am trying to come up with a syntax guide but I am not sure if it is 100% correct. Here it is:

Methods:  
[access modifier | nonaccess modifier] return-type method-name  

Classes:  
[access modifier | nonaccess modifier] class class-name  

Interfaces:  
[access modifier | nonaccess modifier] interface interface-name       

Variables:  
[access modifier | nonaccess modifier] variable-type variale-name  


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.


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.


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.


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜