Java:为什么我不能在main之外调用这个方法?

Tim*_*den 1 java methods program-entry-point object

作为一个初学者,我想知道为什么我的caller.VelocityC唯一作品放在主要区块内?

当我有这样的代码时,我无法调用该方法.

方法调用类:

public class Velocity2 {

VelocityCounter caller = new VelocityCounter();
caller.VelocityC(6, 3);
}
Run Code Online (Sandbox Code Playgroud)

包含方法的类:

public class VelocityCounter {  
void VelocityC(int s, int v){
    System.out.print(s/v);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ted*_*opp 11

在Java中,您不能拥有不属于方法的可执行语句.*第一行没问题:

VelocityCounter caller = new VelocityCounter();
Run Code Online (Sandbox Code Playgroud)

因为编译器认为您正在声明并初始化一个名为callerclass 的实例变量Velocity2.但是第二行:

caller.VelocityC(6, 3);
Run Code Online (Sandbox Code Playgroud)

在类声明的顶层是非法的.

*从技术上讲,这不太对劲.语句也可以出现在构造函数,static块和实例初始化程序块中.