Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling another method from the main method in java [duplicate]

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.

like image 995
kamikaze_pilot Avatar asked Jan 31 '11 08:01

kamikaze_pilot


People also ask

Can I call a method from another method in Java?

Java For TestersWe can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.

Can we call a method twice in Java?

In exactly the same way you would call the method once. You simply have as many statements calling the method as your code requires. So if I have a method to print a string, e.g.: public void printString(String text) {

How do you call a method from the main method in the same class in Java?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.


2 Answers

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.

like image 176
skaffman Avatar answered Sep 17 '22 17:09

skaffman


Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)

If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!

 class Foo{      public static void main(String[] args){        Bar myInstance = new Bar();        myInstance.do(); // works!        Bar.do(); // doesn't work!         Bar.doSomethingStatic(); // works!     }  }  class Bar{     public do() {    // do something    }     public static doSomethingStatic(){    } } 

Also remember, classes in Java should start with an uppercase letter.

like image 28
yan.kun Avatar answered Sep 16 '22 17:09

yan.kun