Java Reference
In-Depth Information
public
Inventory(String n)
//Constructor 2
{
name = n;
itemNum = -1;
price = 0.0;
unitsInStock = 0;
}
public
Inventory(String n,
int
iNum,
double
cost)
//Constructor 3
{
name = n;
itemNum = iNum;
price = cost;
unitsInStock = 0;
}
public
Inventory(String n,
int
iNum,
double
cost,
int
inStock)
//Constructor 4
{
name = n;
itemNum = iNum;
price = cost;
unitsInStock = inStock;
}
8
//Add additional methods
}
This class has four constructors and four instance variables.
Consider the following declarations:
Inventory item1 =
new
Inventory();
Inventory item2 =
new
Inventory("Dryer");
Inventory item3 =
new
Inventory("Washer", 2345, 278.95);
Inventory item4 =
new
Inventory("Toaster", 8231, 34.49, 200);
For
item1
, the default constructor in the line labeled
//Constructor 1
executes
because no value is passed to this variable. For
item2
, the constructor in the line
labeled
//Constructor 2
executes because only one parameter, which is of type
String
, is passed and it matches with that constructor. For
item3
, the constructor
in the line labeled
//Constructor 3
executes because three parameters are passed to
item3
and they match with that constructor. Similarly, for
item4
, the constructor in
the line labeled
//Constructor 4
executes (see Figure 8-14).
Search WWH ::
Custom Search