Java:为什么不能在main之外调用此方法? [英] Java: Why can't I call this method outside of main?

查看:42
本文介绍了Java:为什么不能在main之外调用此方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为初学者,我想知道为什么 caller.VelocityC 仅在放入主块时才起作用?

As a beginner I wonder why my caller.VelocityC only works when put inside of the main block?

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

When i have my code like this, I can't call the method.

方法调用类:

public class Velocity2 {

VelocityCounter caller = new VelocityCounter();
caller.VelocityC(6, 3);
}

包含方法的类:

public class VelocityCounter {  
void VelocityC(int s, int v){
    System.out.print(s/v);
  }
}

推荐答案

在Java中,您不能拥有不属于方法一部分的可执行语句. * 第一行是可以的:

In Java, you can't have executable statements that aren't part of a method.* The first line is okay:

VelocityCounter caller = new VelocityCounter();

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

because the compiler thinks you are declaring and initializing an instance variable named caller for class Velocity2. The second line, however:

caller.VelocityC(6, 3);

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

is illegal at the top level of a class declaration.

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

*Technically, that's not quite right. Statements can also appear in constructors, static blocks, and instance initializer blocks.

这篇关于Java:为什么不能在main之外调用此方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆