Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
  }
}
like image 615
bary Avatar asked May 05 '11 12:05

bary


1 Answers

Use the fully qualified class name:

new com.mypackage.A();
like image 161
Michael Borgwardt Avatar answered Oct 05 '22 23:10

Michael Borgwardt