Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main method in a static inner class.?

Tags:

java

I've learnt that the only public class in a Java file must also have the main method. However, below you can see the main method inside an inner class instead? What is the rule with regard to the main method definition in a source file?

public class TestBed {
    public TestBed() {
        System.out.println("Test bed c'tor");
    }

    @SuppressWarnings("unused")
    private static class Tester {
        public static void main(String[] args) {
            TestBed tb = new TestBed();
            tb.f();
        }
    }

    void f() {
        System.out.println("TestBed::f()");
    }
}
like image 340
Rajat Avatar asked Feb 03 '12 08:02

Rajat


1 Answers

If you want to start a class with java (the Java launcher: java test.MyClass) then this class must have a main method with the well known signature.

You can have a main method with the same signature anywhere you want. But don't expect that the launcher will find it.

P.S. The name of the language is Java, not JAVA.

There is a minor detail:

You may do this:

package test;

public class Test {

    /**
     * @param args the command line arguments
     */
    static public class A {

        public static void main(String[] args) {
            System.err.println("hi");
        }
    }
}

java test.Test$A

but this is non standard ...

like image 150
PeterMmm Avatar answered Oct 21 '22 01:10

PeterMmm