Hani Goc Hani Goc - 1 year ago 88
Java Question

Object instantiation: Inner class and outer class with the same name (Java)

Code description and ouput

In the following code. We have a class TestInners, one inner class A, one method local inner class A and one outer class A.

  1. When we instantiate an object as in
    new A().m();
    the ouput is

  2. In order for the program to output inner we must instantiate the object after the method local inner class A in the gomethod.

  3. If we comment the inner class the program will output outer.


In the code as it is. Why did it output middle? Is there a preference for the inner classes first? then the outer classes? I got confused.

Source code

class A { void m() { System.out.println("outer"); } }

public class TestInners {
public static void main(String[] args) {
new TestInners().go();
void go() {
new A().m();
class A { void m() { System.out.println("inner"); } }

class A { void m() { System.out.println("middle"); } }

Answer Source

Yes, if you shadow symbols with more local definitions, the more local one is chosen. This most frequently happens with method parameters vs instance fields, leading to the famous this.name = name idiom.

In your case, you can get to the outer class by using a fully qualified class name.

But don't name classes like that. Too much confusion for no reason.