Reputation: 4581
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
Reputation: 280171
The rule is the following
The method
main
must be declaredpublic
,static
, andvoid
. It must specify a formal parameter (§8.4.1) whose declared type is array ofString
.
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