加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中的构造函数中使用“this.”

发布时间:2020-12-15 04:10:53 所属栏目:Java 来源:网络整理
导读:我已经设置了这样的构造函数: public class VendingMachine { private double currentBalance; private double itemPrice; private double totalCollected; public VendingMachine(double itemCost) { currentBalance = 0; totalCollected = 0; itemPrice =
我已经设置了这样的构造函数:

public class VendingMachine {

    private double currentBalance;
    private double itemPrice;
    private double totalCollected;

    public VendingMachine(double itemCost) {
        currentBalance = 0;
        totalCollected = 0;
        itemPrice = itemCost;
    }
    ...
}

我的问题是通过接受double itemCost的参数来设置我的构造函数有什么不同.

有什么不同而不是做到:

this.itemPrice = itemCost;

解决方法

在你的情况下,没有区别.如果我们想要将构造函数参数与类字段区分开来,有时需要此组件:

public VendingMachine(double itemPrice) {    // notice the name change here
    itemPrice = itemPrice;         // has no effect
    this.itemPrice = itemPrice;    // correct way to do it
}

来自JLS §6.4.1:

The keyword this can also be used to access a shadowed field x,using the form this.x. Indeed,this idiom typically appears in constructors (07001):

06001

Here,the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general,however,it is considered poor style to have local variables with the same names as fields.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读