简体   繁体   中英

Any way in initialize objects in a constructor that need “this” as a parameter?

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 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. */
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM