Link to home
Start Free TrialLog in
Avatar of techbro
techbroFlag for United States of America

asked on

Inner Class in Java

I compiled and run the code below, and the output is , "middle". Could you please explain why the code prints "middle" instead of "outer"?  I can understand why "inner" does not print because it comes after  - new A().m(); But "Outer" is in the beginning so it does not make sense why "Outer" does not print.

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");
		}
	}
}

Open in new window


Avatar of rodness
rodness
Flag of United States of America image

Within the scope of the go() method, the local class TestInners.A has precedence over the global class A.  As for the class that would print "inner", you are right, it hasn't been defined yet.

This is, of course, why reusing class names, even for inner classes, is a cause for confusion.
thats because the "this" reference is attached to it, it is as good as this.new A()
ASKER CERTIFIED SOLUTION
Avatar of ksivananth
ksivananth
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of techbro

ASKER

Thank your for your response.

One more question before closing.
I tried your code, and it helped me understand how local class has more precedence more global class. It makes sense why the method prints "middle" in line 3, but why "this.new A().m()" prints "middle" in line 12. Without "this", it is printing "inner".

The code is given below:

void go()
{
            this.new A().m();
            class A
            {
                  void m()
                  {
                        System.out.println("Inner");
                  }
            }
            
            this.new A().m();
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>this.new A().m()" prints "middle" in line 12

this is same as test.new A(), simply overriding the default reference. if you simply say new A(), this will refer the inner class with in the go method. when you say this.new A(), you are overriding the default and telling the runtime to refer the class refered by TestInner( nothing but "this" )

>>Without "this", it is printing "inner".

see above
compare it with pointing same file name located in different dir.
Avatar of techbro

ASKER

Thank you for your time!