Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

Method calls inside a Java class

I was setting out to write a piece of code today in Eclipse, and I started out like so:

public class MyClass {
    System.currentTimeMillis();
}

(Ignore the fact that I wasn't thinking straight, etc. etc...)

I get this compile error:

Syntax error on token "currentTimeMillis", Identifier expected after this token

It works if I change that statement to an assignment statement:

long time = System.currentTimeMillis();

Of course, it doesn't cause errors if placed inside a method body and also within blocks inside the class body.

Why is this? Is there some compiler level rule that says that only assignment statements or declarations should be present inside the class body?

TIA

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The class body can only contain declarations.

Specifically, § 8.1.6 of the JLS defines the class body like this:

A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

    ClassBody:
      { ClassBodyDeclarations
opt
}

ClassBodyDeclarations: ClassBodyDeclaration ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration: ClassMemberDeclaration InstanceInitializer StaticInitializer ConstructorDeclaration
ClassMemberDeclaration: FieldDeclaration MethodDeclaration ClassDeclaration InterfaceDeclaration ;

As you can see, there are no statements in there anyway, so a class body may not directly contain a statement.

If you think about it, it makes sense: at which point should that code be executed? There is no context to tell you about that, so it makes no sense.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...