从java中的main方法调用另一个方法 [英] calling another method from the main method in java

查看:419
本文介绍了从java中的main方法调用另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

class foo{

   public static void main(String[] args){
      do();
   }

   public void do(){}


}

但是当我通过运行从 main 调用 do()时命令行上的命令 java foo ,java抱怨你无法从静态函数调用方法。

but then when I call do() from main by running the command java foo on the command line, java complains that you can't call a method from a static function.

所以我的问题是:如何调用main方法中的方法,如果不可能,在使用java命令从命令行运行程序后调用方法的替代策略是什么。

So my question is: How do you call methods from the main method and if it is not possible what are some alternative strategies to call methods after the program is run from the command line using the java command.

推荐答案

你只能调用像 do()这样的实例方法(这是一个非法的方法名,顺便提一下)对类的一个实例:

You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

public static void main(String[] args){
  new Foo().doSomething();
}

public void doSomething(){}

或者,make doSomething() static,如果适用于您的设计。

Alternatively, make doSomething() static as well, if that works for your design.

这篇关于从java中的main方法调用另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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