package cn.zuoy.test; public class Goods { private int id; private String name; private double price; private String desc; //封装 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } //重写toString()方法 // 可以直接显示数据 @Override public String toString() { return "Goods{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", desc='" + desc + '\'' + '}'; } //无参构造器 public Goods() { super(); } //有参构造器 public Goods(int id, String name, double price, String desc) { this.id = id; this.name = name; this.price = price; this.desc = desc; } }
package cn.zuoy.test; //柜台类 public class Counter { //柜台商品列表,固定10个商品位置 Goods[] goods = new Goods[10]; //无参构造器初始化2个商品 public Counter(){ this.goods[0]=new Goods(1001,"巧克力",25,"美味可口,恋爱必备!"); this.goods[1]=new Goods(1002,"卫龙辣条",1,"隔壁小孩馋哭了!"); } // 展示柜台所有的商品(不能输出null) public void show(){ for (int i = 0; i < goods.length; i++) { if(goods[i]!=null){ System.out.println(goods[i]); } } } }
package cn.zuoy.test; //测试类 public class CounterTest { public static void main(String[] args) { //创建柜台对象,调用show()方法展示柜台商品 Counter counter = new Counter(); //调用show()方法展示柜台商品 counter.show(); } }