Method calls inside a Java class

前端 未结 8 2122
难免孤独
难免孤独 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:07

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

    Yes. More specifically, the syntactic rules of programming languages are usually defined as a formal grammar that specifies how syntactically correct programs are formed. In this case, the Java language specification says:

    ClassBody:
        { ClassBodyDeclarationsopt }
    
    ClassBodyDeclarations:
        ClassBodyDeclaration
        ClassBodyDeclarations ClassBodyDeclaration
    
    ClassBodyDeclaration:
        ClassMemberDeclaration
        InstanceInitializer
        StaticInitializer
        ConstructorDeclaration
    

    Since a static method call is not one of ClassMemberDeclaration, InstanceInitializer, StaticInitializer and ConstructorDeclaration, it's not allowed to be present directly inside a class body.

提交回复
热议问题