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()
void 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
Solution 1:
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.
Solution 2:
See http://checkstyle.sourceforge.net/config_modifier.html.
The correct (or rather, conventional) order is :
- public
- protected
- private
- abstract
- static
- final
- transient
- volatile
- synchronized
- native
- strictfp
This order should come naturally to your mind after some days programming in Java.
Solution 3:
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.
Solution 4:
Modifiers go before the class
or a type. According to the Java Language Specification, order between modifiers does not matter.
Solution 5:
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.