Search code examples
javaclassclassloaderaccess-modifiers

Java File with all non public classes with one of them having a main method


I just came across this weird scenario while playing :-)

Java's documentation specifies that a file can contain all non public classes and the file name not matching any of the class. When one tries to run after compilation it will generate Exception even after one of the classes having main method specified. Explanation is needed as to how to execute this file's main method.

My test code is as follows in file named NoPublicClasses.java:

class Class1{

}

class Class2{
public static void main(String[] args){

}

}

It compiles well. but if you try to run this it will throw exception. Below you can check what I tried

java NoPublicClasses  

For the above I expected an Exception and it happened as I expected but when I did

java Class2

It also threw exception which was unexpected. So I need some kind person to explain the reason or if there's any solution to this issue without changing access modifier and file name or class name please let me know.

Thanks and regards.


Solution

  • Your second example should work normally. Make sure you are executing the correct class (i.e. don't confuse it with the file name). Quoting form JLS specification -section 1.2. Example Programs:

    Most of the example programs given in the text are ready to be executed and are similar in form to:

    class Test {
        public static void main(String[] args) {
            for (int i = 0; i < args.length; i++)
                System.out.print(i == 0 ? args[i] : " " + args[i]);
            System.out.println();
        } 
    }
    

    On a machine with the Oracle JDK installed, this class, stored in the file Test.java, can be compiled and executed by giving the commands:

    javac Test.java 
    java Test Hello, world.
    

    producing the output:

    Hello, world.
    

    The JLS uses programs where top level classes are not public. And I am able to run the above example as it is described above. I have used a filename named AAA.java though it produces a Test.class when compiled.