James Oravec James Oravec - 1 year ago 82
Java Question

Java Inner Classes Design Benifits

In java, you can have inner classes. I'm curious from a design perspective if there are any benefits to this.

My initial thoughts are that having a separate file with the class is cleaner in separating things into reusable modules. By doing so, if other classes wish to use that other class, they can also make their own instances. To me it seems like avoiding the inner classes may be a better design for extensibility and code reuse, and when working on new projects, its normally hard to tell if the class would be reused or not... so I feel siding on having the separate classes is the way to go.

I ask this question because I took over a project which has a bunch of these... which makes me think the previous developer may of just been lazy or unfamiliar with the IDE. But I want to make sure I'm not missing any benefits that these inner classes have. If there are benefits can someone let me know, and then I can confirm if the previous developer was taking advantage of these benefits.

Answer Source

Inner classes are good when they are not used outside the containing class - it's a way of curtailing class bloat. As a general rule, that's the only time I use them.

Non-static inner classes also have access to the containing instance's private fields.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download