public class Item {
    // 成员变量
    private String code;
    private String name;
    private String type;
    private double price;
    private static int totalNum = 0;

    // 构造器
    public Item() {
        totalNum++;
    }

    public Item(String code, String name) {
        this.code = code;
        this.name = name;
        totalNum++;
    }

    // Getter和Setter方法
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public static int getTotalNum() {
        return totalNum;
    }

    public static void setTotalNum(int totalNum) {
        Item.totalNum = totalNum;
    }

    public static void main(String[] args) {
        Item computer1 = new Item();
        computer1.setCode("666");
        computer1.setName("戴尔(DELL) 游戏笔记本");
        computer1.setType("游戏");
        computer1.setPrice(5499.00);

        Item computer2 = new Item("007", "苹果(Macbook pro)笔记本");
        computer2.setType("电脑,办公");
        computer2.setPrice(18000.00);

        System.out.println("商品1名称:" + computer1.getName());
        System.out.println("商品1价格:" + computer1.getPrice());

        System.out.println("商品2名称:" + computer2.getName());
        System.out.println("商品2价格:" + computer2.getPrice());

        System.out.println("总商品数量:" + Item.getTotalNum());
    }
}

输出结果:

商品1名称:戴尔(DELL) 游戏笔记本 商品1价格:5499.0 商品2名称:苹果(Macbook pro)笔记本 商品2价格:18000.0 总商品数量:2

Java 商品类 Item 实现:构造器、Getter/Setter、商品数量统计

原文地址: https://www.cveoy.top/t/topic/p00w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录