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
The four access modifiers in Java are public, protected, default, and private.
Java language provides a total of 12 modifiers. They are public, private, protected, default, final, synchronized, abstract, native, strictfp, transient, and volatile.
By now, you are quite familiar with the public keyword that appears in almost all of our examples: public class Main. The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.
Simply put, there are four access modifiers: public, private, protected and default (no keyword).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With