views:

197

answers:

2

I have a java file TestThis.java like 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. My question is that 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 do Java even permits compiling of such files without a top-level class?

A: 

Any other class in the same package can access A and B; in this can the null package is being used since no package statement is present for the source file.

Software Monkey
+4  A: 

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.

Ivan Dubrov