views:

580

answers:

6

Are inner classes commonly used in Java? Are these the same as nested classes? Or have these been replaced in Java by something better? I have a book on version 5 and it has an example using an inner class, but I thought I read somewere that inner classes were "bad."

I have no idea and was hoping for thoughts on it.

Thank you.

+9  A: 

Inner classes are frequently used, and something very similar - anonymous classes - are practically indispensable, as they are the closest thing Java has to closures. So if you can't remember where you heard that inner classes are bad, try to forget about it!

Daniel Earwicker
just don't mention double-brace initializers...
skaffman
closures are basically allowing a snippet of code to be shipped somewhere else, and still refer to its original surroundings. It can be very, very nice.
Thorbjørn Ravn Andersen
@skaffman - ack! Just looked them up, couldn't quite believe it. You think you've created a List<int>? Guess again, my friend, guess again!
Daniel Earwicker
+2  A: 

I don't think they are evil or bad. Maybe they are not widely used, but they do have many uses,callbacks being one of them. A special advantage is that they can extend from a different class than the outer class, so you could have multiple inheritance.

I would say that one of the issues with inner classes is that their syntax is somewhat "ugly". That's something that discourages some people. Here at work there are many of them.

Tom
+4  A: 

They're not "bad" as such.

They can be subject to abuse (inner classes of inner classes, for example). As soon as my inner class spans more than a few lines, I prefer to extract it into its own class. It aids readability, and testing in some instances.

There's one gotcha which isn't immediately obvious, and worth remembering. Any non-static inner class will have an implicit reference to the surrounding outer class (an implicit 'this ' reference). This isn't normally an issue, but if you come to serialise the inner class (say, using XStream), you'll find that this can cause you unexpected grief.

Brian Agnew
A: 

They are useful and can be very commonly used. While you should be cautious about abusing the functionality, they aren't much more liable to be abused than any other language feature.

McWafflestix
+2  A: 

A good example of an inner class is the iterator implementation for a given collection type. Its a class that implements a public interface, but has no business existing except in association with another class. It allows you to model things that in C++ you would be forced to do with the friend operator.

Jherico
A: 

Non-static inner classes can hide a performance problem. They do have access to member fields on the enclosing class, but not directly, but via getters which are created automatically. This will be slower then just copying the members of the enclosing class to the inner class.

Some other problems with non-static inner classes are described here

quant_dev