Programming Language - Java

Inner Class

Inner class is an effective way to encapsulate local data structure in another class. For example, LinkedList could have a local data structure ListNode. Inner class could access variables of the outer class.

Static and Non-static inner class

The difference between static and non-static class is on the instantiate and accessibility. Like normal static method/variable, static inner class cann’t access non-static member of the outer class, and non-static inner class could access all memeber of outer class.

Similary to static member and method, static class could be instantiated directly from class, e.g.,

    OuterClass.StaticInner staticInner = new OuterClass.StaticInner();

Non-static class need a object to actually instantiate it, like normal non-static member/method need a object.

    OuterClass outerClass = new OuterClass();
    OuterClass.InnerClass innerClass = outerClass.new InnerClass();

Access Restriction

  • Outer class could access inner member no matter what access restriction is put (private, public, protected);
  • If a inner class is private, then client is not able to access it. Only public inner class could be accessed/instantiated from client.
Written on August 16, 2021