Accessing top level class without top level class in Java
I have a Java file TestThis.java
as shown below:
class A
{
public void foo()
{
System.out.println("Executing foo");
}
}
class B
{
public void bar()
{
System.out.println("Executing bar");
}
}
The above code file compiles without any warnings / errors. Is there a way to access any A
or B
no top-level class from any other outer class?
If not, why does Java even allow compilation of such files without a top-level class?
0
source to share
2 answers
As usual (e.g. accessed from 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 there cannot be more than one public class in a source file. If you have, the file name must match the public class name. Otherwise (your case) you can name your file whatever you want. Other, non-public classes will appear in the package and you can access them as usual.
+5
source to share