File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Access modifier for members of method local inner class. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Access modifier for members of method local inner class." Watch "Access modifier for members of method local inner class." New topic

Access modifier for members of method local inner class.

Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
As Method local inner class are accisible only within the method in which its declared and hence a method local inner classs is not visible outside the method in which its declared. As a result of this it does not make any sense to have access like public,protected and default access to the members of the method local inner class because we can never pass a reference to a method local inner class instance to any other method because the inner classs will not be visible outside.
Is my understanding correct? If yes then why does compiler allow the memebers of the method local inner class to have above modifiers?

Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
You could have one method local inner class extend another, in which case it would matter whether your members are private or not. For example, this compile isn't legal:
You have to change the access modifier of to default, protected, or public for the above program to compile.

(I do agree that this is rarely useful in practice, though.)

SCJP 5.0
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Often, local classes may implement interfaces, in which case they must implement public methods. Likewise in inner class may extend another class (not just another inner class) - in which case, it must use appropriate access modifiers when overriding methods.

It's true that there may be many methods and fields of local classes for which access modifiers are irrelevant. I usually just omit modifiers in this case, rather than typing "public" or "private" and letting the reader wonder what that means. Of course, a default modifier means something too. But the point is, if you need a particular type of modifier, use it, and if it doesn't matter what modifier you use, don't worry about it.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Access modifier for members of method local inner class.
It's not a secret anymore!