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.
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.
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) {
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With