First Java project distinguishing between different instances of class -
this first java application have built, have created class products, need declare 4 different instances of products can access each individual product in different parts of code. code have @ moment shown below can seem acces last product have created:
products = new products(1,2.50,"coke",15); products = new products(2,1.50,"crisps",5); products = new products(3,2.00,"juice",2); products = new products(4,2.50,"chocolate",0); system.out.println(products.getproductid()+ " " + products.getproductname());
is there way 'where product id equal to' or assign individual name each instance of product? appolagies if question has been asked elsewhere had through related posts couldn't find on related java. code below shows products class:
public class products { private int productid; private double productprice; private string productname; private int productstock; public products(int id, double price,string pname,int stock){ productid = id; productprice = price; productname = pname; productstock = stock; } public void setproductid(int id){ productid = id; } public void setproductprice(double price){ productprice = price; } public void setproductname(string pname){ productname = pname; } public void setproductstock(int stock){ productstock = stock; } public int getproductid(){ return productid; } public double getproductprice(){ return productprice; } public string getproductname(){ return productname; } public int getproductstock(){ return productstock; }
thanks in advance help.
you should name variables different if aren't (you didn't show variable names ...) or make kind of collection (arraylist, list, etc.). eg.
products coke = new products(1,2.50,"coke",15); products crisps = new products(2,1.50,"crisps",5); products juice = new products(3,2.00,"juice",2); products chocolate = new products(4,2.50,"chocolate",0); system.out.println(coke.getproductid()+ " " + juice.getproductname());
eg. 2
hashmap<integer, products> products = new hashmap<integer, products>(); products.put(products.size(), coke); products.put(products.size(), crisps); products.put(products.size(), juice); products.put(products.size(), chocolate); system.out.println(products.get(1).getproductid() + " " + products.get(1).getproductname());
Comments
Post a Comment