EMZETT.
Login

Inner Classes

In short: A class defined within another class — useful when a helper class is conceptually closely tied to its surrounding class and doesn’t make sense on its own outside it.

In more detail: Inner classes can (depending on the language) have access to the private fields of their surrounding class, which distinguishes them from completely independent classes. A special form is the anonymous class — an inner class with no name of its own, defined directly at the spot where it’s needed once.

In Depth

The main reason to use an inner class instead of a separate, standalone one is logical grouping: if a helper class only makes sense at all in the context of its outer class (e.g. a Node within a hand-built LinkedList), the nesting makes this relationship immediately visible in the code, instead of only mentioning it in documentation.

class LinkedList {
    class Node {       // only makes sense within LinkedList
        value
        next
    }
    head: Node
}

Roughly two variants are distinguished:

  • Non-static inner class: needs an instance of the outer class to even be created, and automatically has access to its fields — closely coupled to a specific outer object.
  • Static inner class (in languages that distinguish this, e.g. Java): behaves almost like a normal, standalone class, but is still organised in the outer class’s namespace — needs NO instance of the outer class and has no automatic access to its non-static fields.

The advantage over a completely separate file/class is encapsulated, tidy structure — related code is found in one place instead of scattered across several files. The downside: if the inner class does end up needing to be reused elsewhere, its tight coupling to its outer class is often in the way, and a refactor into a standalone class becomes necessary.

See also: Classes, Anonymous Classes