Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Main - Calling another method

Tags:

java

I have the following code below:

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

i get this error: Non-static method start() cannot be referenced from a static context.

How can i go about doing this?

like image 217
Benji Avatar asked Feb 13 '26 09:02

Benji


2 Answers

Create an instance of your class and call the start method of that instance. If your class is named Foo then use the following code in your main method:

    Foo f = new Foo();
    f.start();

Alternatively, make method start static, by declaring it as static.

like image 160
Simon C Avatar answered Feb 14 '26 21:02

Simon C


Hope this can help you..

public class testProgarm {

    private static void start() {
        System.out.println("Test");
    }

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

}

However, it is not a good practice to make a method static. You should instantiate a object and call a object's method instead. If your object does't have a state, or you need to implement a helper method, static is the way to go.

like image 41
TheOneTeam Avatar answered Feb 14 '26 23:02

TheOneTeam