This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Code for Method-Local Inner Classes not compiling

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method-Local Inner Classes, Chapter 8, Sierra/Bates:



What is wrong with my code? The compiler outputs:

MyOuter2.java:19: cannot find symbol
symbol : class MyInner
location: class MyOuter2
MyOuter2.MyInner inner = new MyOuter2().new MyInner();
^
MyOuter2.java:19: cannot find symbol
symbol : class MyInner
location: class MyOuter2
MyOuter2.MyInner inner = new MyOuter2().new MyInner();
^
2 errors
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot access a method local inner class out the method it is defined. As the name suggests, it is kind of local variable to the method and the scope of inner class is limited within the method. However you can access the method like below:

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rajeev,

I tried your code while compiles and runs; how do I get seeOuter() to execute?

I've tried several options, but none of them work, please assist.
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandra Bachan wrote:Hi Rajeev,

I tried your code while compiles and runs; how do I get seeOuter() to execute?

I've tried several options, but none of them work, please assist.
Hi Sandra, please see my code. While calling new MyOuter2().doStuff(), doStuff() will call seeOuter();


Otherwise you could call
inside doStuff()


Try to run my code, it gives output of seeOuter();
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandra Bachan wrote:Hi Rajeev,

I tried your code while compiles and runs; how do I get seeOuter() to execute?

I've tried several options, but none of them work, please assist.


Try the below code...
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Rajeev: Tried your code, it now works.

@ Abimaran: Tried your code, and now understand more about inner classes. Ran the code with MyOuter obj = new MyOuter2().doStuff(); and then replaced it with MyOuter obj = new MyOuter(); and saw the difference in output.

Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic