Java Inner classes

A nested class is a member of its enclosing class. Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object.

There are three reasons you might create a nested class:

Organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won’t be used in any other context.
Access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
Convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context.

Related Tags

Tutorials

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.