1、this 自引用

2021-03-11  本文已影响0人  爱学习的代代

当一个类中的属性和方法里的参数或者局部变量有重名的时候,需要通过this这个关键词来访问初始化对象的实例变量。

例子说明:定义了一个商品类,定义了几个常见的属性,如下图。其中有个count字段表示了当前该商品的库存个数。

程序功能说明: 初始化一个牙刷商品,库存个数为200, 进行库存检查,当小于500,就进行货物的补充。

image.png

附录测试代码:

// 1、Merchandise.java 
public class Merchandise {
    int id;
//  商品名称
    String name;
//  库存个数
    int count;
//  售价
    double soldPrice;
//  进价
    double purchasingRrice;



//  对商品的库存进行修改
    public void changeCount(int count) {
        System.out.println("给商品补货" + count + "个");
        this.count += count;
    }

//  查看商品的库存是否够数据
    public Boolean countIsEnough() {
        if (this.count < 500) {
            System.out.println("商品的个数为"+ this.count + "。库存不足,请补货");
            return false;

        }
        else {
            System.out.printf("商品的个数充足");
            return true;
        }

    }

//  生成get、set 方法
    public void setCount(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setPurchasingRrice(double purchasingRrice) {
        this.purchasingRrice = purchasingRrice;
    }

    public double getPurchasingRrice() {
        return purchasingRrice;
    }

    public void setSoldPrice(double soldPrice) {
        this.soldPrice = soldPrice;
    }

    public double getSoldPrice() {
        return soldPrice;
    }
}




测试类:

//2、TestMerchandise

public class TestMerchandise {
    public static void main(String[] args) {
        int MAX_COUNT = 500;
        Merchandise m = new Merchandise();
        m.id = 1;
        m.name = "牙刷";
        m.count = 200;
        m.purchasingRrice = 2.3;
        m.soldPrice = 5;


        if (m.countIsEnough() == false) {
            int addCount = MAX_COUNT - m.count;
            m.changeCount(addCount);
        } else {

        }

        System.out.printf(m.name + "商品的库存是:" + m.count);

    }
}


上一篇 下一篇

猜你喜欢

热点阅读