Java: The meaning of 'this' (with examples)

The this keyword 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;
Continue 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) {
    // ...
}
Continue here: this(…) constructor call (with examples)

Comments

Be the first to comment!