Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inner Classes Design Benefits

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.

like image 916
James Oravec Avatar asked Apr 18 '13 13:04

James Oravec


2 Answers

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.

like image 66
Bohemian Avatar answered Oct 23 '22 03:10

Bohemian


Inner classes are useful to:

  1. Hide implementation details.

  2. Make project view more concise and thus understandable.

  3. Add logical grouping of the related code.

like image 30
Vitaly Avatar answered Oct 23 '22 03:10

Vitaly