Java - when “this” is the only way to go?

后端 未结 5 1073
眼角桃花
眼角桃花 2021-01-28 13:21

The following code runs for both var = putVar; & this.var = putVar;

I understand: \"this\" is used to identify that - \"put this value for just \'my\'

5条回答
  •  终归单人心
    2021-01-28 13:35

    You can use this if you're using the same method argument identifier as a field, but it can be avoided if you simply do not use the same name.

    Not using the same name is a more common practice to avoid confusion and shadowing. Hence, any reference to this in a setter can be replaced with a better naming standard: inParameter, for instance.

    public void setX(int inX) {
        x = inX;
    }
    

    The other use of this would be to explicitly invoke a constructor. This is a form which can't be replaced with a simpler naming convention:

    public class Foo {
    
        private String name;
    
        public Foo() {
            this("");
        }
    
        public Foo(String inName) {
            name = inName;
        }
    }
    

    There may also be a case in which you want to return the instance you're working with. This is also something that this allows you to do:

    return this;
    

提交回复
热议问题