I'm designing a class hierarchy and I come across the problem as my title, here is a smaller abstraction of it:
public abstract class A {
private C c;
public A(C c) {
this.c = c;
}
// ...
}
public class B extends A {
private int a;
private int b;
// ...
public B(int a, int b, ... /* and more but no object of C */) {
super(new C(this)); // <-- this is the point, got error:
// can't access `this` .
this.a = a;
this.b = b;
// ...
}
}
public class C {
private A a;
public C(A a) {
this.a = a;
}
}
In short: A
needs to keep a reference to C
, vice versa, but both should be done in their constructor, and after the construction of both, the fields A a
and C c
should not be changed so I made them private
. So in this situation what's the best practice?
The following is actually not a good example, but the point is that I have a situation need to do what the above try to do.
(More context: Now let's say I change private C c;
of class A
into
private List<C> someCs;
that is: A
is a container of C
's, so during some situation those C
's need to be sorted. And for some client of each C
, the client needs to know what's its parent, i.e. which A
it belongs to. In this situation I need references of both directions.)