I was setting out to write a piece of code today in Eclipse, and I started out like so:
public class MyClass {
System.currentTimeMillis();
}
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.