Let's say I have two classes, named A and B, that are associated with each other such that it is most convenient if each class's object contains a reference to the other. In other words, class A has a variable "b" of class B. Class B has a variable "a" of class A. This way, the code in each class has easy access to the other class.
Is there any way to set up this association to be "final"? i.e. variable b in class A is final and variable a in class B is final? It seems that setting up these references in a constructor (as would be required by the final keyword) requires an illogical circular sort of reference.
This is more of a conceptual question than a practical one. Thanks!
Do you really need both classes to depend on each other? A stack overflow has nothing to do with classes referencing each other. It is perfectly possible and supported by Java to do that. The Exception is caused by a too deep recursin, this can happen with one method/class as well.
If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class. If you try it gives you a compile time error.
A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type.
Note that you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
Yes it is possible, if one of the class is responsible for creating the instance of the other class. The first constructor can pass an instance of itself as a parameter for the second class.
public class A {
final B b;
public A() {
b = new B(this);
}
public B getB() {
return b;
}
}
public class B {
final A a;
public B(A a) {
this.a = a;
}
}
As another poster pointed out, it is possible to do this by making one of the classes responsible for constructing the other and passing itself into the constructor for the other object.
However, this lends itself to potential issues if you want one instance of the first class to correspond to one instance of the second class (which it seems you do). Another object could potentially pass an existing reference to the first class into the constructor for the second class, thus allowing an invalid situation (the an instance of the second class now has a reference to an instance of the first class which references a different instance of the second class).
More potential issues arise when you consider that the second class' constructor cannot reference uninitialized members of the first class.
My suggestion is that if the two classes are so interrelated that you want them to each have final references to the other, just make them the same class. Then you've always got a final reference to the other object: this
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With