java “this” keyword proper use

前端 未结 3 1186
[愿得一人]
[愿得一人] 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:43

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

提交回复
热议问题