This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes local inner class vs anonymous inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "local inner class vs anonymous inner class" Watch "local inner class vs anonymous inner class" New topic
Author

local inner class vs anonymous inner class

John Eipe
Ranch Hand

Joined: May 23, 2008
Posts: 205
Hi

I was reading Inner Classes

and came through 2 types of inner classes - local and anonymous.

Could someone explain the differences with a sample code?

Thanks.


www.cs-repository.info
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Local inner class means, a class declared inside a method. And, anonymous means, a class created on the FLY.


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32689
    
    4
There are examples of anonymous classes here, and in the older links mentioned.
A local class would look something like thisI'll let you work out how many bits of bad design there are in that code
[edit]Remove one erroneous } and new line from code[edit]
Alex Hurtt
Ranch Hand

Joined: Oct 26, 2010
Posts: 98
In sticking with Campbell's example, an anonymous class would look like this:



Difference here is you create an actual concrete implementation of the Comparator interface "on the fly" and give it no name/reference assignment. You can't refer back to it later or anything.
This can be useful if/when you have no other use for the Comparator outside the scope where it is used for example. It looks wierd at first to those who are not used to it because you are using the 'new' keyword to instantiate an Interface which you normally can't do except when you are making an implementation of it at the same time like this.
John Eipe
Ranch Hand

Joined: May 23, 2008
Posts: 205
Thanks a ton!

Anonymous classes well explained!!!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32689
    
    4
You're welcome
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: local inner class vs anonymous inner class
 
Similar Threads
making a mostly anonymous Comparator be Serializable
40% for Devakas Final Exam
error message why?
Java Rule Round-up (#104)
Nested and Inner Class