Skip to content

Java, Inner Class

I was going through various online sources on Java inner classes, and thought I’d summarize the notes here. This blog post does assume that the reader is familiar with what a local and anonymous inner class is, and will instead talk about some of the interesting properties.

Inner class contains a implicit reference of the Outer class instance it belongs to.

public class A {
    public class B {
        private int var = 0;

        private A refParent() {
            return A.this;

We see that the implicit reference to parent can actually be obtained through [InstanceNameOfParentClass].this

This property means that an instance of an inner class is attached to the instance of the outer class. A significant implication here is that the outer class cannot be garbage collected for as long as a strong reference to the inner class exists somewhere, because the inner class implicitly references the parent.

Creating an instance to a inner class
If the inner class is not private (or protected if you are out of package), then you can instance the inner class through a special new operator

A a = new A();
A.B b = B();

Notice that a instance of the outer class must be created first before generating the instance of the inner class (due to the required implicit reference)

You cannot declare static members in a non-static inner class
This happens because an inner class is linked to a parent instance, thus it cannot contain any static members itself. However if the inner class is static, then it is allowed to have static members and it will not contain a reference to the outer class.

Only nested classes can be declared static (Why use it?)
Why do we use static inner classes? Simple, you can use the inner class without a reference to the outer class (since it doesnt contain any reference to it, and can be instanced through [ClassName].[NestedClassName]

Private methods and variables in the inner class are accessible to parent (vice versa)

Noting that since inner class is treated as a member of the outer class, they have access to each other’s private members

Posted in Java. Tagged with , , , .