简体   繁体   中英

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??

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
    }
}

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM