6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaのmainメソッドがstaticであることをお嘆きのあなたに

Posted at

動機

ちょっとした動作確認で、mainメソッドから簡単なプログラムを書くことってありますよね。
今時はJShellがあるので、そういう機会もあまりないのかもしれないですが。(どっちやねん)

ともかく、mainメソッドはstaticなので何かと面倒、なんとかしたい、という場合の話。

やること

mainメソッドで自分自身のインスタンスを作って、インスタンスメソッドを実行すればいいです。

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

public void execute() {
    ...
}

余談

競技プログラミングの場合だと、mainメソッドに事前処理事後処理と実装用のインスタンスメソッドの呼び出しを記述したテンプレートを用意すると何かと捗ります。

例えば私はこういうテンプレートを作ってます。

テンプレート抜粋
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();
    }
// (以下自作Scannerの実装)

この辺は人によっていろいろな流儀があるので、いろんな競プロerのソースコードを参考にするといいと思います。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?