Alexey Romanov
Alexey Romanov

Reputation: 170723

Why is this$0 field of an inner class not private?

Java inner classes store the reference to the outer instance in a synthetic field:

class A {
    class B {}
}

java.util.Arrays.toString(A.B.class.getDeclaredFields())
// [final A A$B.this$0]

What I am wondering is why this field isn't generated as private.

It can't be accessed by the programmer without reflection (outside B, where A.this refers to it).

The obvious guess is that you can write something in A (outside B) which needs to access it, but I can't think of any such case.

Upvotes: 2

Views: 585

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

I was thinking in the wrong direction. It isn't A that needs to access B.this$0, but potential inner classes of B itself!

If we have

class A {
    class B {
        class C {}
    }
}

then after desugaring C becomes

class A$B$C {
    final A$B this$1;

    A$B$C(A$B b) {
        this$1 = b;
    }
}

and A.this inside C has to be accessed as this$1.this$0. Alternatively, it could have two fields

    final A$B this$1;
    final A this$0;

in which case the constructor would contain this$0 = b.this$0; (this was actually what I expected before checking).

Upvotes: 1

Related Questions