Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
315 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...