Java - (Inner|Nested) Class

> Procedural Languages > Java

1 - About

The Java programming language allows you to define a class within another class.

Advertising

3 - Nested or Inner ?

  • Nested classes that are declared static are called static nested classes.
  • Non-static nested classes are called inner classes and requires an instance of the outer class to be referenced.
class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
}

4 - When to use ?

  • If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.
  • It increases encapsulation but increase dependency

If you want to implement an hierarchy like of object see also Tree - Composite (Design Pattern)

5 - Documentation / Reference

lang/java/nested_class.txt · Last modified: 2017/09/13 16:15 by gerardnico