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 Method-Local Inner Classes? 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 "Method-Local Inner Classes?" Watch "Method-Local Inner Classes?" New topic

Method-Local Inner Classes?

Minhaj Mehmood
Ranch Hand

Joined: Jan 22, 2007
Posts: 400

Can anyone give me the example of Method-Local Inner Classes on-job(usage in real life) example?

SCJP6 96% | SCWCD5 81% | SCDJWS5 79%
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

I have never used one and never found the reason to use one.

I did encounter it once when maintaining some code. A programmer had used a local class to hold the values that a JDBC database call returned. These values were put into an object and used immediately. It was a pretty long method. I thought it made the method look ugly and if the class were to be used somewhere else, it would not be possible. I try to avoid method local inner classes

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Waclaw Borowiec

Joined: Dec 14, 2009
Posts: 21
I found these kind of classes useful in a scenario when I was sending a message to another part of a system and I waited for an asynchronous reply in a separate thread. The code looked somewhat like this:

ReplyThread is not used anywhere else bedside this method so in terms of scope there's no need for it to be declared on higher level i.e. as an inner or a top level class. Of course for someone readability can have higher priority than the narrowest possible scope.
Minhaj Mehmood
Ranch Hand

Joined: Jan 22, 2007
Posts: 400

I see - Thanks for the code Waclaw Borowiec
I agree. Here's the link:
subject: Method-Local Inner Classes?
It's not a secret anymore!