Reputation: 103
I am teaching myself java, and I am really enjoying it, however I have come to the "Anonymous Class" subject, and I am trying to understand when, and where you would even use this, from what my book says it is a very popular class, but I can't seem to get my head around it, I understand how to create them. but i was just looking for a bit more information, so i can start implementing them in my classes.
I would really appreciate some examples, and a bit more explanation on when it would be useful to use them.
Upvotes: 2
Views: 373
Reputation: 96385
First, you never need an anonymous class. You can always create a named class. When you're starting out, the main reason to learn about anonymous classes is to recognize them in code you read.
You use an anonymous class in cases where you want to create some object to use it only once (so it's not worthwhile to give a name to the type, put it in its own file, etc.). Mostly they come in handy in event-driven programming, such as using Swing. Your event handler is typically a one-off that is specific to the control you're plugging it into, so there's no point giving it a name.
For event handlers it's common to need access to the surrounding object, so it's convenient for the event handler to be an inner class, and its references to the surrounding context mean it's not reusable at all.
Good starting examples are in the Oracle Java tutorial. The classes FileFilter and FilenameFilter in the java.io package are often used with anonymous classes to specify what files the filter should return.
In Java 8 lambdas give you a better way to create single-use instances of classes with only one method.
Upvotes: 9
Reputation: 37645
If you write a named class SomeClass
, then realise you only need to write new SomeClass
once, it often makes more sense to use an anonymous class instead.
You should only do this if the body of the class is short (otherwise readability suffers) and if you couldn't use a lambda or method reference instead.
Upvotes: 0