Eutherpy
Eutherpy

Reputation: 4581

NetBeans running Java program with main in non-public class

I know that there were plenty of questions like this, but in all of them, the answers were "you cannot run a Java program with main method in a non-public class". (What if main method is inside "non public class" of java file?)

However, I tried such a situation in NetBeans, and it ran perfectly fine. Why?

Is having a main in a public class a convention or a strict rule?

Upvotes: 1

Views: 127

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280171

The rule is the following

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

There is however no restriction on the accessibility of the enclosing class. Note however that top level classes cannot be private or protected. Maybe that's where your confusion arises.

You can very well have

class Example {
    private static class Other {
        public static void main(String[] args) throws Exception {
            System.out.println("main in Other");
        }
    }
}

and execute

> java Example$Other

That would show

main in Other

I don't know why you would, but you can.

Upvotes: 1

Related Questions