I know I have done this before but I am getting my constructor order of execution in a twist I think....
public class Class1
{
Class2 _class2;
public Class1()
{
_class2 = new Class2(this);
}
}
public class Class2
{
Class1 _parent; //corrected typo
public Class2(Class1 parent)
{
_parent = parent;
}
}
trouble is that parent always ends up null.
What's the proper way to do this? (maybe I can blame my slowness on having a cold..)
EDITED TO CORRECT THE TYPO (which isn't the problem in the real code!)
The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.
You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays.
Constructors can be passed as arugments to methods using a method reference, somewhat like a function pointer in C++. This can be a Function type with one argument or a BiFunction type with two arguments, either way its a lambda returning a class of the type it constructs.
This should, technically, work, provided you change Class2 to include this.parent = parent;
However, I don't recommend this. I would, instead, recommend lazy initializing your class2 instance inside class1. Depending on what all is done in the constructor of Class2, you can potentially lead yourself into nasty situations.
Making a Class2 property on class1 and lazy initializing it would cause Class2 to be constructed after Class1's constructor is completed, not during it's construction, which is most likely less error prone if your classes get more complicated.
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