system.out.println语句在java中的任何方法之外

use*_*893 12 java program-entry-point

我的问题是我们不能在java之外写一个输出声明吗?如果我将它括在{}括号中,那么我不会得到错误,但如果我直接写它,我会收到错误.为什么这样?

public class abc 
{ 
   int a=3; 
   int b=0; 
   System.out.println("this statement gives error"); //Error!! 
   {System.out.println("this works fine");} 
   public static void main(String args[]) {

   System.out.println("main"); 
      abc t=new abc();
   }
} 
Run Code Online (Sandbox Code Playgroud)

我尝试用main编写它,它的工作原理.如果没有方法,它为什么不工作?

Kon*_*Kon 8

将它括在大括号中时,将它放在初始化块中,该块在实例化类时运行.除变量声明/初始化之外的任何语句都不能在Java中的方法或初始化块之外进行.


JNL*_*JNL 5

AClass只能有属性或方法。

是从中创建单个对象的蓝图。

    int a=3;   // attributes
    int b=0;   // attributes
    System.out.println("this statement gives error"); //Error!! 

    {System.out.println("this works fine");}  // init block whenever an object is created.
                                              // since it is inside { }
Run Code Online (Sandbox Code Playgroud)