下面一行简单的java代码报错,请问为什么 ?

The Java Language Specification, Third Edition [1] 第 8.1.6 节 [2]:

-
A class body may contain declarations of members of the class, that is, fields (§8.3)
-
第 8.3 节 [3]:

-
The variables of a class type are introduced by field declarations:
FieldDeclaration:
FieldModifiers(opt) Type VariableDeclarators ;

VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator

VariableDeclarator:
VariableDeclaratorId
VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:
Identifier
VariableDeclaratorId [ ]

VariableInitializer:
Expression
ArrayInitializer
-
以上规定的意思就是——仅仅针对你提供的例子而言——在声明类成员(field)的时候,要写成

类型 变量声明 ;

的形式。其中变量声明(VariableDeclarator)又可以写成

变量名 = 变量初始化表达式

的形式。这里最重要的是,定义一个成员变量的时候,必须写出它的类型,所以按照你的写法,编译器出错的原因,就是因为这种写法不符合语法上的规定。

合乎规定的写法比如(不完全列表):

public int alpha = 1;
public int a, b, c = 2;
public int d = 2, e = 3;
float f;
int g[] = {1, 2, 3};
String h = randomString();

此外,如果你把例子改成

public class Mytest { int a = 1; int a = 2; }

也就是重新定义一次 a ,结果仍旧会报错,虽然这样写合乎上面说的语法,但仍旧是一个错误,因为第 8.3 节里又规定说:

-
It is a compile-time error for the body of a class declaration to declare two fields with the same name.
-
综上所述,报错的原因就是……设计 Java 语言的人规定你不可以这么写。

[1] java.sun.com/docs/books
[2] java.sun.com/docs/books
[3] java.sun.com/docs/books

(顺便抱怨一下,知乎的编辑器实在 反 人 类。
原发布于 https://www.zhihu.com/question/20007902/answer/13643420