I am having an issue with declaring and initializing object arrays within Java using jGrasp. This is an assignment and I copied the code straight from the book and changed the class and array name. I have tried assigning and initializing without an array by using 'itemA, itemB, itemC' with the same duplicate output as you can see at the bottom of the code.
Driver class:
class Driver
{
public static void main(String[] args)
{
RetailItem[] item = new RetailItem[3];
item[0] = new RetailItem("a", 1, 1);
item[1] = new RetailItem("b", 2, 2);
item[2] = new RetailItem("c", 3, 3);
for (int i = 0; i < item.length; i++)
{
System.out.printf("item: " + item[i].getItemName());
}
}
The output results in:
item: c
item: c
item: c
I do not understand as I am a beginner as to why the output is always the last array object initialized.
The output that I am attempting is:
item: a
item: b
item: c
Here is my RetailItem class:
class RetailItem
{
private static String itemName;
private static int unitsOnHand;
private static double priceEach;
//Constructor(s)
public RetailItem(String name, int qty, double price)
{
itemName = name;
unitsOnHand = qty;
priceEach = price;
}
//Public Methods
public static double getPriceEach()
{
return priceEach;
}
public static String getItemName()
{
return itemName;
}
public static int getUnitsOnHand()
{
return unitsOnHand;
}
}
static? Why are you using it?