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

那年仲夏 提交于 2019-12-12 05:26:20

问题


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.

Here is the error I'm getting.

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?


回答1:


You can't call a method directly from the java class body.

Create a constructor in your Test class, and put the print in it :

class Test {
    int a = 100;

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

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.




回答2:


From Declaring Classes in the Java tutorial:

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, {}.

You can't make any function calls outside of a method declaration.



来源:https://stackoverflow.com/questions/28390438/why-do-i-get-a-compilation-error-when-calling-println-method-in-the-class-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!