Method calls inside a Java class

前端 未结 8 2340
难免孤独
难免孤独 2020-11-28 15:31

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

public class MyClass {
    System.currentTimeMillis();
}
         


        
8条回答
  •  甜味超标
    2020-11-28 16:00

    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:
          { ClassBodyDeclarationsopt }
    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.

提交回复
热议问题