为什么在 class 体中调用 println 方法会出现编译错误? #Java

Why do I get a compilation error when calling println method in the class body? #Java

class Test {
    int a = 100;
    System.out.println(a); 
}
class Demo {
    public static void main(String args[]) {
        Test t = new Test();
    }
}

我是编程新手。我在练习时发现了这段代码。我不明白为什么会出现此错误。

这是我遇到的错误。

Demo.java:3: error: <identifier> expected
 System.out.println(a);
                   ^
Demo.java:3: error: <identifier> expected
 System.out.println(a);
                     ^
2 errors
Compilation failed.

你们能解释一下为什么我会收到这个错误吗?

您不能直接从 java class body.

调用方法

在您的 Test class 中创建一个构造函数,并将 print 放入其中:

class Test {
    int a = 100;

    public Test() {
        System.out.println(a); 
    }
}

请注意,如果出于某种原因您确实希望在不使用构造函数的情况下加载 class 时执行语句,您可以定义一个 static 块,这里是一个示例:

class Test {
    static int a = 100;

    static {
        System.out.println(a); 
    }

}

但是,这仅供参考,您的情况确实不需要。

来自 Java 教程中的 Declaring Classes

In general, class declarations can include these components, in order:

  1. Modifiers such as public, private, and a number of others that you will encounter later.

  2. The class name, with the initial letter capitalized by convention.

  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

  5. The class body, surrounded by braces, {}.

您不能在方法声明之外进行任何函数调用。