javajvmclassloader

Accessing non top-level class without a top level class in Java


I have a Java file TestThis.java like the following:

class A
{
    public void foo() 
    {
        System.out.println("Executing foo");
    }
}

class B
{
    public void bar()
    {
        System.out.println("Executing bar");
    }
}

The above code file is compiling fine without any warnings/errors. Is there any way I could access any of class A or B without a top level class from any other external class?

If no then why does Java even permit compiling of such files without a top-level class?


Solution

  • As usual (for example, accessing from the Test.java):

    public class Test {
        public static void main(String... args) {
            A a = new A();
            a.foo();
            B b = new B();
            b.bar();
        }
    }
    

    The rule here is that you could not have more than one public class in the source file. If you have one, the filename must match this public class name. Otherwise (your case), you can name your file as you wish. Other, non-public classes, will be package-visible and you can access them as usual.