Reputation: 537
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!
Upvotes: 0
Views: 815
Reputation: 269797
You can do what you've shown. Why do you think it won't work?
The only limitation is passing this
to the superclass constructor (which is a much rarer temptation). For example, you can't do this:
public class SomeSubclass extends SomeSuperclass {
public SomeSubclass() {
super(this); /* ERROR: Can't pass `this` to super-ctor. */
}
}
Upvotes: 1
Reputation: 317
I've always used initialize() methods for this. I guess you might be able to spawn some form of thread that runs after object creation, but that's a terrible idea. As far as doing it within the constructor, as you initially asked, I don't see how that would work.
To use a car analogy, you're in the middle of building a car (SomeOtherClass), but are unsure of its state of completion. You want the car to drive on a road (SomeClass), but to use that road you need a complete car. So doing what you say would be like passing the road an engine and expecting everything to work out. It just doesn't make sense in OOP terms.
TL;DR: Use an init() method as you suggested and call it a day.
Upvotes: 0