To you who lament that Java's main method is static

Motivation

You may write a simple program from the main method with a little operation check. Now that I have JShell, I may not have many opportunities to do that. (Which one)

Anyway, since the main method is static, it's a story when you want to do something troublesome.

things to do

You can create your own instance with the main method and execute the instance method.

Main.java


public class Main {
    public static void main(String[] args) {
        new Main().execute();
    }
}

public void execute() {
    ...
}

Digression

In the case of competitive programming, if you prepare a template that describes the pre-processing and post-processing and the call of the instance method for implementation in the main method, something will be done.

For example, I am making a template like this.

Template excerpt


public class Main {
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        InputStreamScanner in = new InputStreamScanner(System.in);
        new Main().solve(in, out);
        out.flush();
    }

    private void solve(InputStreamScanner in, PrintWriter out) {
        in.nextInt();

        out.println();
    }
//(Hereafter, implementation of self-made Scanner)

There are various styles in this area depending on the person, so I think you should refer to the source code of various competitive professionals.

Recommended Posts

To you who lament that Java's main method is static
To you who lament that the conversion of JODConverter + LibreOffice is slow
20 Corresponds to static method invocation
Use Modifier # isStatic to determine if the [Reflection] method is static.
To you who absolutely need backtrace
To you who say "JDK 9 is out, but my maintenance target app is JDK 6"
What is the main method in Java?
Write code that is difficult to test
What to do when you want to delete a migration file that is "NO FILE"
Find a value that is convenient to have a method and make it a ValueObject