bary bary - 20 days ago 10
Java Question

Java inner class with the same name as other top level class

I have question related to Java inner classes.

Is there a way to access top level class A from top level class Main that define inner class A?

Below is sample code demonstrating the problem:

class A { // Outer Class A
{
System.out.println("A outer");
}
}

class B { // Outer Class B
{
System.out.println("B outer");
}
}

public class Main {
class A { // Inner Class A
{
System.out.println("A inner");
}
}

public void newA() {
class A { // Local Class A
{
System.out.println("A local");
}
}
new A();
}

public static void main(String[] args) {
new Main().newA(); // prints "A local"
new Main().new A(); // prints "A inner"
//new A(); // compiler error: No enclosing instance of type Main is Accessible.
new B(); // but this works and prints "B outer"
}
}

Answer

Use the fully qualified class name:

new com.mypackage.A();