When should I use “this” in a class?

后端 未结 18 2175
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  广开言路
    2020-11-22 00:06

    Google turned up a page on the Sun site that discusses this a bit.

    You're right about the variable; this can indeed be used to differentiate a method variable from a class field.

        private int x;
        public void setX(int x) {
            this.x=x;
        }
    

    However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:

        private int x;
        public void setX(int newX) {
            x=newX;
        }
    

    Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.

    As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.

提交回复
热议问题