Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the main method in Java have to be static?

Does the main method (that Java requests you have in a class) have to be static? For example I have this code

public class Sheet {

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

    public void myMethod() {
        System.out.println("hi there");
    }

}

This is giving me the error

cannot make a static reference to the non-static call method from main

If I'm getting it clear, any method I call from the main method must be static, and every method I call from a static method must be static.

Why does my whole class (and if we go further, my whole program) and methods have to be static? And how can I avoid this?

like image 553
homerun Avatar asked Jun 13 '26 05:06

homerun


2 Answers

Not all your methods must be static, only the main entry point for your application. All the other methods can remain non-static but you will need to use a reference of the class to use them.

Here's how your code would look like:

public class Sheet {
    public static void main(String[] args) {
        Sheet sheet = new Sheet();
        sheet.myMethod();
    }

    public void myMethod(){
        System.out.println("hi there");
    }
}

The explanation for your concerns are explained here (there's no need to dup all the info here):

  • Why is the Java main method static?
  • What does the 'static' keyword do in a class?
  • In laymans terms, what does 'static' mean in Java?
like image 95
Luiggi Mendoza Avatar answered Jun 14 '26 17:06

Luiggi Mendoza


Your main method must be static because that is the single point of entry in your program for that running configuration.

A static method is bound to the class, hence it cannot know about single instances of that class.

You can invoke myMethod by instantiating your Sheet class:

new Sheet().myMethod();
like image 31
Mena Avatar answered Jun 14 '26 17:06

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!