Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
like image 804
ziggy Avatar asked Aug 13 '11 11:08

ziggy


People also ask

What are the modifiers in Java?

The four access modifiers in Java are public, protected, default, and private.

What are the 12 access modifiers in Java?

Java language provides a total of 12 modifiers. They are public, private, protected, default, final, synchronized, abstract, native, strictfp, transient, and volatile.

What is a modifier in Java explain with proper example?

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.

How many modifiers are there in Java?

Simply put, there are four access modifiers: public, private, protected and default (no keyword).


1 Answers

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.

like image 89
João Silva Avatar answered Oct 27 '22 14:10

João Silva