Java 修饰符语法和格式 [英] 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?
是否有任何关于它们在代码中出现的格式和顺序的描述?我正在尝试提出一个语法指南,但我不确定它是否 100% 正确.这是:
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
推荐答案
来自官方 语法:
Modifier:
Annotation | public | protected | private
static | abstract | final | native | synchronized
transient | volatile | strictfp
ClassOrInterfaceDeclaration:
{Modifier} (ClassDeclaration | InterfaceDeclaration)
ClassBodyDeclaration:
{Modifier} MethodOrFieldDecl
MethodOrFieldDecl:
Type Identifier MethodOrFieldRest
因此,对于类和接口,修饰符必须总是出现在 class
关键字之前,并且以任何顺序出现.例如,final public class
是有效的,但 class final
不是.对于方法和字段,是一样的,只是修饰符必须出现在类型之前.
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.
这篇关于Java 修饰符语法和格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!