varunj6v1k9
varunj6v1k9

Reputation: 43

non-static main method in eclipse

I just started learning java using eclipse IDE. I noticed that main method has to be static else it throws error. Because of this I have to declare many Scanner class' objects for each user-given input. Is there a way to make the main method non-static or defining main method without the static keyword in eclipse??

Upvotes: 0

Views: 668

Answers (3)

AnonymousUser
AnonymousUser

Reputation: 11

The main method is the first method that JVM looks for during compilation. This main method has to be executed even before the instantiation of any object of the class. so that later these instantiated objects will invoke other required methods. And hence, static will help the main to run before object instantiation. It is not possible to run the main method without the static keyword.

Upvotes: 1

Saeed
Saeed

Reputation: 43

The answer is no. You can have a look at these links too:

[A Closer Look at the "Hello World!" Application] (https://docs.oracle.com/javase/tutorial/getStarted/application/index.html)

Why is the Java main method static?

Upvotes: 0

Jens Schauder
Jens Schauder

Reputation: 82008

Is there a way to make the main method non-static or defining main method without the static keyword [...]?

No, this is part of how java works. There is no way around it. But it shouldn't impact your application since you can always create an instance of your main class and call another method on it:

public class X {

    public static void main(String args[]) {
        new X().nonStaticMain();
    }

    public void nonStaticMain() {
        // just pretend this is your main
    }
}

Upvotes: 1

Related Questions