I’m creating a new object ‘baby’ from within class ‘mother’ which implements an interface containing one method ‘feed’ (the names are just for illustration).
How can I pass a pointer to the ‘mother’ class through the constructor of the ‘baby’ class?
I want the baby class to be able to call the ‘feed’ method at any time throughout its lifetime.
What I had tried so far always produced compiler errors.
Constructor of baby class
public Baby(String name, Mother mother) {
this.mother=mother;
this.name=name;
}
Code used to create the baby object (inside Mother class)
Baby baby = new Baby("Brian",this);
You can’t pass
thisinsidestaticcontext, e.g. as astaticfield, in astatic {}initializer or in astatic method()method. The static context applies to the class itself, not to a particular instance.Do the job in the constructor or non-static field/method of
Motherinstead.