I am working on my first Java program as a piece of homework. The task is to have a cataloging program to store and manipulate some products.
I have two classes, a catalog class and a product class. The product class stores data about my products (ID, Price, Color). The catalog list contains an array of products.
My code for the catalog goes something like this:
public class Catalog()
{
static Product[] productList;
Catalog () {
productList = new Product[99];
}
populateCatalog {
// Assign each item product in the product array an ID, Price & Color
}
}
The productList does not change throughout the program, therefore is it bad practice to add the code from the populateCatalog method to the constructor?
What you are doing in the constructor is fine. Another option is just to initialize the
productListwhen you declare it, likestatic Product[] productList = new Product[99];However….
you dont want
productListto be static. As it stands right now, eachCatalogueinstance does NOT have aproductList; the class as whole has oneproductListthat it shares among all instances (which is whatstaticmeans). It makes sense for each catalog to have its own product list right? So change your declaration to beprivate Product[] productList;That way every instance of Catalog will have its own productList.