Nested classes

Nested classes are used for

  • logically grouping classes that are only used in one place
  • increasing encapsulation
  • to keep code readable and maintainable

static nested class

The static nested class behave like other top-level class. But it can access to private member of the outer class instance.

class OuterClass {
     public static class NestedClass{
         // ...
     }
}
Code example

inner classes

The non-static nested classes are called inner classes. Anonymous and local classes are special kinds of inner classes.

Inner class can't declare the static members.

Instance of the inner class can be created only from instance of outer class. Instance of the inner class has hidden reference to outer object that allows to have access to the outer object members directly.

Members of the inner object shadow members of the outer class with same name. The OuterClassName.this construction resolves this problem.

class OuterClass{
    private class InnerClass{
        // ...
    }
}
Code example

anonymous classes

Anonymous classes enable you to declare and instantiate a class at the same time. They are useful when you need a small implementation of an interface or abstract class in place.

Implementation of interfaces with one abstract method may be replaced by lambdas.

Actually anonymous means that Java compiler will generate name.

Code example

local classes

Local classes are defined in a block, typically in the body of a method.