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
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 :
This order should come naturally to your mind after some days programming in Java.
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.
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.