gpt4 book ai didi

java - Java中构造函数中 "this."的使用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:28:33 24 4
gpt4 key购买 nike

我的构造函数是这样设置的:

public class VendingMachine {

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

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

我的问题是,通过接受双 itemCost 的参数来设置我的构造函数有什么区别。

与制作它有什么区别:

this.itemPrice = itemCost;

最佳答案

在您的情况下不会有任何区别。如果我们想区分构造函数参数和类字段,有时需要 this 组件:

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 (§8.8):

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

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.

关于java - Java中构造函数中 "this."的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com