Reputation: 3
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;
}
}
Upvotes: 0
Views: 47
Reputation: 1249
The problem is that you're setting the itemName, unitsOnHand, and priceEach as static
. Basically this means that all instances of RetailItem will have the same value for each of those variables. If you remove the static
keyword each instance will have their own itemName, unisOnHand, and priceEach variables.
Upvotes: 0
Reputation: 17188
Your problem is that itemName
(and all your other variables) have been declared static
. This binds them to the class, not to an instance, so when your constructor alters itemName
, it alters that variable for the whole class.
To see what I mean by "class variable", try this: define a main
method in RetailItem
that looks like this:
public static void main(String[] args) {
// Print the property of the RetailItem *class*: remember, you don't even have an instance of the class at this point.
System.out.println(RetailItem.itemName); // null
RetailItem item = new RetailItem("a", 1, 1);
// Print the property of the class again, ignoring the instance that you created.
System.out.println(RetailItem.itemName); // "a"
}
To resolve this, just remove the static
declaration from anything you intend to be an instance variable (as well as the setters/getters!).
private String itemName;
public String getItemName() {
return itemName;
}
Upvotes: 1