I ran into the problem in Java, but I guess it’s a question about OOP in general. It should be a pretty common need, so I hope there’s a solution I’m just unaware of.
What do you do when you need to initialize an object’s fields within the constructor, but those objects need this as a parameter?
So this is what you can’t do:
public class SomeClass {
private SomeOtherClass foo;
public SomeClass (SomeOtherClass foo) {
this.foo = foo;
}
}
public class SomeOtherClass {
private SomeClass bar;
public SomeOtherClass() {
bar = new SomeClass(this);
}
}
I don’t know about any solution except having an init() method that does all object initialization, and calling it after I initialize the SomeOtherClass object in my main program. Is there a better way? Or is there a way to make a method of SomeOtherClass (the init() method) run after the constructor is complete, without calling it explicitly?
Thanks!
You can do what you’ve shown. Why do you think it won’t work?
The only limitation is passing
thisto the superclass constructor (which is a much rarer temptation). For example, you can’t do this: