homerun
homerun

Reputation: 20765

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?

Upvotes: 2

Views: 3283

Answers (4)

Teja P
Teja P

Reputation: 11

Yes the main method has to be static, Because we will not create any object for main method. And static methods can be invoked directly at the time of class loading. As they are loaded at time of class loading, we do not have to create any object for it !!

And as we know, static is mainly for memory management. All the static methods and variables can be accessed directly used the class name. Of course we can create object for static methods and variables to access them. But it is a wastage of memory.

Not all of your methods needs to be static. Depending upon your prescribed application we can use methods as static.

Upvotes: 1

Adriaan Koster
Adriaan Koster

Reputation: 16209

Create an instance:

public class Sheet {

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

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

Upvotes: 2

Mena
Mena

Reputation: 48434

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();

Upvotes: 3

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

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

Upvotes: 10

Related Questions