为什么在类主体中调用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();
}
}
我是编程新手。我在练习时发现了这段代码。我不明白为什么会收到此错误。
I'm new to programming. I found this code when I'm practicing. I don't understand why I'm getting this error.
这是我遇到的错误。
Demo.java:3: error: <identifier> expected
System.out.println(a);
^
Demo.java:3: error: <identifier> expected
System.out.println(a);
^
2 errors
Compilation failed.
你们能解释为什么我遇到此错误吗?
Can you guys explain why I'm getting this error?
推荐答案
您不能直接从 java类主体
调用方法。
You can't call a method directly from the java class body
.
在 Test
类中创建一个构造函数,然后在其中放入 print
: / p>
Create a constructor in your Test
class, and put the print
in it :
class Test {
int a = 100;
public Test() {
System.out.println(a);
}
}
请注意,如果出于某些原因,您确实想要声明要在不使用构造函数的情况下加载类时执行,可以定义 static
块,此处为示例:
Note that if for some reason you really want a statement to be executed when the class is loaded without using a constructor, you can define a static
block, here an example :
class Test {
static int a = 100;
static {
System.out.println(a);
}
}
但是,这仅供参考并且在您的情况下确实不需要。
However, this is just for reference and really not needed in your case.
这篇关于为什么在类主体中调用println方法时出现编译错误? #Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!