java “this” keyword proper use

落爺英雄遲暮 提交于 2020-01-21 09:27:09

问题


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 ");
    } 
}

I also have a method :

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

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.


回答1:


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.




回答2:


Both the cases you mentioned will work fine.

Use of this is a good practice as its more readable due to our english mindset, When we say this.some_variable, we get a mental image of some_variable inside the current class

this keyword is also helpful in avoiding variable shadowing




回答3:


I think you have a bit of a confusion on how the "this" keyword works.

Let me give you an example:

This

public class testing {
    private int a;
    private int b;

    testing(int a,int b){
        this.a = a;
        this.b = b;
    }
}

is the same as:

public class testing {
    private int a;
    private int b;

    testing(int x,int y){
        this.a = x;
        this.b = y;
    }
}

Which of course for the second one would be easier to put if we do it like this:

public class testing {
    private int a;
    private int b;

    testing(int x,int y){
        a = x;
        b = y;
    }
}


来源:https://stackoverflow.com/questions/28805295/java-this-keyword-proper-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!