• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Inner classes

 
K Raj Kumar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers!

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

Output:middle
Source: SCJP6 Study guide, Kathy sierra and Bert bates, Selftest, Inner classes, page 688.
Help needed.Thanks in advance!
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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


Here class A is declare after new A().m(), so it will not find "inner".



Here inner class A shadows the outer class A, so "middle" will be output.
 
Sushant Kaushik
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Punit

Here inner class A shadows the outer class A, so "middle" will be output.


You mean to say middle class A shadows the outer class A, as inner class is not visible when new A().m()was called, Correct?
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as inner class is not visible when new A().m()was called, Correct?


Method local inner class is not visible when new A().m() is called.
 
Sushant Kaushik
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it..Thanks
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think few closing curly braces (}) are missing in the code :roll: ...
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shushant,

could you post the correct code again.('}' are missing it seems)

Thanks
Preetha
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Watching the output, this would be the correct code

 
Sushant Kaushik
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit. Just to add, if I put the inner A before calling go() then it will call inner A as this inner class is visible at Line 1.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic