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
推荐答案
官方 语法 Java编程语言(简化):
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
因此,对于类和接口,修饰符必须始终会在类
关键字之前,以任何顺序显示。例如, 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屋!