在Java中的构造函数中使用“this.”
我已经设置了这样的构造函数:
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:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |