java “this” keyword proper use

前端 未结 3 1177
[愿得一人]
[愿得一人] 2021-01-15 02:01

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

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


        
3条回答
  •  离开以前
    2021-01-15 02:50

    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;
        ...
    }
    

    Both multiply versions are the same.

提交回复
热议问题