Method calls inside a Java class return an “identifier expected after this token” error

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.

Leave a Comment