方法调用Java类 [英] Method calls inside a Java class

查看:120
本文介绍了方法调用Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始在Eclipse中编写一段代码,我开始是这样的:

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...)

我得到这个编译错误:

令牌currentTimeMillis上的语法错误,此令牌后预期的标识符

如果我将该语句更改为赋值语句,则此方法有效:

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

推荐答案

类主体只能包含声明。

具体来说,§8.1.6的JLS 定义了这样的类体:

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


类主体可能包含类成员的声明,即字段(§8.3),类(§8.5),接口(§8.5)和方法(§8.4)。类主体也可以包含实例初始化程序(§8.6),静态初始化程序(§8.7),以及构造函数的声明(§8.8)为班级。

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.

这篇关于方法调用Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆