Search code examples
javamethodsstaticprogram-entry-point

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?


Solution

  • 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):