Java: Why can't I call this method outside of main? [closed]

非 Y 不嫁゛ 提交于 2021-02-04 05:16:31

问题


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.

Method calling class:

public class Velocity2 {

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

Class containing the method:

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

回答1:


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

VelocityCounter caller = new VelocityCounter();

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.

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




回答2:


That's because code outside of methods or constructors is only declarative. You can't put statements like assignment or method calls outside of methods or constructors.




回答3:


That area of the source file is where you can declare fields of the class or fields of the instances, but if you still really want to call caller.VelocityC(6, 3); then you can use a instance initialization block like the following:

public class Velocity2 {

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

caller.VelocityC(6, 3); would execute during every construction of Velocity2, just like the execution of VelocityCounter constructior and assignment to caller.

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html



来源:https://stackoverflow.com/questions/24686721/java-why-cant-i-call-this-method-outside-of-main

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