Originally Posted by
fahman_khan75@yahoo.com
I’m trying to simplify my constructor by using “this” reference variable. I’m aware how to use this reference when making constructors that involve fields of primitive data types; however, not so sure fields involving objects.
I'm not entirely sure if I completely understand your post, but it appears there is some confusion with the "this" keyword. The "this" keyword has 2 uses: (1) to refer to a field in the class, and (2) to call another constructor in the same class. See
Using the this Keyword (The Java™ Tutorials > Learning the Java Language > Classes and Objects).
In the code in post #1,
Originally Posted by
fahman_khan75@yahoo.com
public RetailItem()
{
this("",0,0,0,?);
}
"this" (not a reference variable) is used to call the 5-parameter version of the constructor, which is
public RetailItem(String description, int Item_number, double Retail, double wholesale, CostData object)
Since the 5th parameter is of type CostData, all you need to do is to create an instance of CostData, and pass the reference to the instance of CostData in place of '?'. However, since the "this" constructor call must be the first statement in a constructor, you'll need to do the CostData instantiation inline, e.g.,
this("", 0, 0, 0, new CostData(0, 0));
The above will
not work with your current implementation of the CostData inner class because the inner class (CostData) has an implicit reference to an instance of the outer class (RetailItem). The inner class can be instantiated only after the outer class is instantiated unless the inner class is static. Therefore to do the above you'll need to change CostData so that it looks like the following:
private static class CostData
An alternative will be to move CostData out of RetailItem so that CostData is no longer an inner class, and instead becomes a "regular" class. This way you don't need to make CostData static.
Finally, in the 5-parameter constructor since an instance of CostData is being passed in via the "object" parameter, you only need to assign it to the cost field, i.e.,
public RetailItem(String description, int Item_number, double Retail, double wholesale,
CostData object) {
this.description = description;
this.Item_Number = Item_Number;
this.cost = object;
}
Btw, the above excerpt has a small error. "this.Item_Number = Item_Number;" has no effect because Item_Number (with uppercase 'N') is the field name, whereas the constructor's 2nd parameter name is Item_number (with a lowercase 'n'). I would highly recommend that you follow the Java code convention. See
Code Conventions for the Java Programming Language.