What is the meaning of “this” in Java?

后端 未结 21 2917
走了就别回头了
走了就别回头了 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 06:04

    Quoting an article at programming.guide:


    this has two uses in a Java program.

    1. As a reference to the current object

    The syntax in this case usually looks something like

    this.someVariable = someVariable;
    

    This type of use is described here: The 'this' reference (with examples)

    2. To call a different constructor

    The syntax in this case typically looks something like

    MyClass() {
        this(DEFAULT_VALUE); // delegate to other constructor
    }
    
    MyClass(int value) {
        // ...
    }
    

    This type of use is described here: this(…) constructor call (with examples)

提交回复
热议问题