定义数组存储 3 个商品对象。商品的属性:商品的 id,名字,价格,库存。创建三个商品对象,并把商品对象存入到数组当中。
//对象数组 1
package demo01;
public class Goods {private int goodsid;private String goodsName;private double goodsPrice;private int goodsInventory;public Goods() {}public Goods(int goodsid, String goodsName, double goodsPrice, int goodsInventory) {this.goodsid = goodsid;this.goodsName = goodsName;this.goodsPrice = goodsPrice;this.goodsInventory = goodsInventory;}public int getGoodsid() {return goodsid;}public void setGoodsid(int goodsid) {this.goodsid = goodsid;}public String getGoodsName() {return goodsName;}public void setGoodsName(String goodsName) {this.goodsName = goodsName;}public double getGoodsPrice() {return goodsPrice;}public void setGoodsPrice(double goodsPrice) {this.goodsPrice = goodsPrice;}public int getGoodsInventory() {return goodsInventory;}public void setGoodsInventory(int goodsInventory) {this.goodsInventory = goodsInventory;}
}
//对象数组 1
package demo01;
public class GoodsDemo {public static void main(String[] args) {Goods g1 = new Goods(111, "苏打水", 3.5, 20);Goods g2 = new Goods(222, "西瓜", 0.6, 10);Goods g3 = new Goods(333, "运动鞋", 399.9, 6);Goods[] arr = new Goods[3];arr[0] = g1;arr[1] = g2;arr[2] = g3;for(int i = 0; i < arr.length; i++) {System.out.println(arr[i].getGoodsid() + "-" + arr[i].getGoodsName() + "-" + arr[i].getGoodsPrice() + "-" + arr[i].getGoodsInventory());}}
}
运行结果: