使用"这个".在Java中的构造函数中

use*_*861 3 java constructor

我已经设置了这样的构造函数:

public class VendingMachine {

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

    public VendingMachine(double itemCost) {
        currentBalance = 0;
        totalCollected = 0;
        itemPrice = itemCost;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

有什么不同而不是做到:

this.itemPrice = itemCost;
Run Code Online (Sandbox Code Playgroud)

ars*_*jii 5

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

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

JLS §6.4.1:

该关键字this还可用于x使用表单访问阴影字段this.x.实际上,这个成语通常出现在构造函数中(§8.8):

  
class Pair {
    Object first, second;
    public Pair(Object first, Object second) {
        this.first = first;
        this.second = second;
    }
}

这里,构造函数采用与要初始化的字段具有相同名称的参数.这比为参数创建不同的名称更简单,并且在这种风格化的上下文中不会太混乱.但是,一般情况下,使用与字段名称相同的局部变量被认为是不好的样式.