What is the meaning of “this” in Java?

后端 未结 21 2640
走了就别回头了
走了就别回头了 2020-11-21 05:41

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if i

21条回答
  •  星月不相逢
    2020-11-21 05:56

    It refers to the current instance of a particular object, so you could write something like

    public Object getMe() {
        return this;
    }
    

    A common use-case of this is to prevent shadowing. Take the following example:

    public class Person {
        private final String name;
    
        public Person(String name) {
            // how would we initialize the field using parameter?
            // we can't do: name = name;
        }
    }
    

    In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

    public class Person {
        private final String name;
    
        public Person(String name) {
            this.name = name;
        }
    }
    

提交回复
热议问题