本文介绍了java" this"关键字正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的构造函数中有一个使用关键字this的Fraction类:

I have a Fraction class using keyword this in my constructor:

public Fraction(int numerator, int denominator)
{
    this.numerator = numerator;
    this.denominator = denominator;
    adjustSigns();

    if(this.denominator == 0 )
    {
     throw new FractionException(" Undefined Fraction ");
    }
}

我还有一个方法:

 public FractionInterface multiply(FractionInterface secondFraction)
 {
    Fraction second = (Fraction) secondFraction;
    Fraction answer = new Fraction ((numerator * second.numerator), (denominator * second.denominator));
    answer.reduceToLowestTerms();
    return answer;
}

上面的方法在编译和运行时工作正常但是这个版本:

The above method works fine when I compile and run but so this this version:

 public FractionInterface multiply(FractionInterface secondFraction)
 {
    Fraction second = (Fraction) secondFraction;
    Fraction answer = new Fraction ((this.numerator * second.numerator), (this.denominator * second.denominator));
    answer.reduceToLowestTerms();
    return answer;
 }

我的问题是哪一个是正确的?如果在我的构造函数中使用this关键字,我还必须在我的方法中使用它吗?再次,他们都工作正常,做他们应该做的事情,但我想知道哪种方式是正确的方式。谢谢。

My question is which one is correct ?? If use the "this" keyword in my constructor do I also have to use it in my methods ?? Again, they both work fine and do what they are supposed to do but I want to know which way is the correct way. Thanks.

推荐答案

如果您想要区分,必须明确使用在局部变量和同名成员之间。否则,它是可选的。

Using this explicitly is mandatory if you wish to distinguish between a local variable and a member of the same name. Otherwise, it is optional.

您的构造函数不会将传递值分配给没有的实例成员。前缀,因为方法参数会隐藏实例成员。如果你给参数赋予不同的名字,你可以不用这个。

Your constructor won't assign the passes values to the instance members without the this. prefix, since the method arguments would hide the instance members. If you give the arguments different names, you can do without the this. :

public Fraction(int num, int denom)
{
    numerator = num;
    denominator = denom;
    ...
}

两者乘以版本是一样的。

这篇关于java" this"关键字正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 02:22