I have code like the following:
class A {
final Object data;
A(Object _data) {
data = _data;
}
class B extends A {
B() {
super(new C());
}
class C { }
}
}
I get following error message:
Cannot reference 'C' before supertype constructor has been called
I don't understand why it is not possible.
Are there any workarounds? I want data
to be final and classes to be nested as they are in the code above (I don't want to create a different file for each class, because classes are quite small and in my real code it would be more logical for them to be nested)
The problem is that non-static inner classes need an instance of the outer class before they can be instantiated. That's why you can even access fields of the outer class directly in the inner class.
Make the inner classes static
and it should work. In general it's a good pattern to use static inner classes instead of non-static. See Joshua Bloch's Effective Java item 22 for more information.
class A {
final Object data;
A(final Object _data) {
data = _data;
}
static class B extends A {
B() {
super(new C());
}
static class C {
}
}
}