techbro
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");
}
}
}
thats because the "this" reference is attached to it, it is as good as this.new A()
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
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();
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>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
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.
ASKER
Thank you for your time!
This is, of course, why reusing class names, even for inner classes, is a cause for confusion.