calling another method from the main method in java

kamikaze_pilot picture kamikaze_pilot · Jan 31, 2011 · Viewed 269.1k times · Source

I have

class foo{

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

   public void do(){}


}

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.

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.

Answer

skaffman picture skaffman · Jan 31, 2011

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(){}

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