2013-06-03 32 views
3

构造我已经把我的构造是这样的:使用“this”。在Java中

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; 
+3

在你的情况,没有任何区别。如果该属性与构造函数参数名称相同,则需要'this.var = var;' – jlordo

+0

另请参见:http://stackoverflow.com/q/957502/5812 –

回答

5

在你的情况下,不会有任何区别。该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

关键字this也可以用于使用表格this.x访问阴影字段x。的确,这种习惯用法通常显示在构造(§8.8):

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

这里,构造函数采用具有相同的名称作为参数进行初始化的字段。这比为参数发明不同的名称更简单,并且在这种程式化的背景下不会太混乱。然而,通常情况下,使用与字段名称相同的本地变量被认为是不好的样式。

1

它这种情况下,它其实并不重要。这将有所作为,如果你有参数的同名像属性

public VendingMachine(double itemPrice) { 
    this.itemPrice = itemPrice; 
} 

那么你就需要区分哪一个是类的成员,哪一个是方法范围变量。因此,这是this关键字所服务的内容(您也可以使用它来调用其他类构造函数等)。

但是,约定是给予类属性和方法参数相同,并使用this关键字来防止混淆。

0
this.itemPrice = itemCost; 

。在你的例子没有实际的区别。 itemPrice已经在该方法的范围内。当在方法中声明另一个变量itemPrice时会出现差异。为了区分成员变量和局部变量,我们使用this

1

这是确定分配给你做的方式,但一般在Java中,我们遵循正确的命名规则,我们通常会保留名称,有像你的情况不存在误解......

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

这里'this'是指调用哪个方法的对象,因此最终将接收到的itemPrice分配给对象状态(变量)itemPrice。