Java The this(Keyword)

www.laut‮irut‬.com
Java The this(Keyword)

In Java, the this keyword refers to the current instance of an object. It is used to refer to the object's own member variables and methods, and it can also be used to call one constructor from another within the same class.

Here's an example of how the this keyword can be used to refer to an object's member variables and methods:

public class Example {
  private int value;

  public Example(int value) {
    this.value = value;  // "this" refers to the current object
  }

  public void setValue(int value) {
    this.value = value;  // "this" refers to the current object
  }

  public int getValue() {
    return this.value;  // "this" refers to the current object
  }
}

In this example, the this keyword is used to refer to the value member variable of the Example class. Without the this keyword, it would be ambiguous whether we are referring to the local value parameter or the value member variable.

The this keyword can also be used to call one constructor from another within the same class. This is often done to reuse code or to ensure that all constructors in the class follow a certain pattern.

Here's an example of how the this keyword can be used to call one constructor from another:

public class Example {
  private int value;

  public Example() {
    this(0);  // call the Example(int) constructor with a default value
  }

  public Example(int value) {
    this.value = value;  // "this" refers to the current object
  }
}

In this example, the Example() constructor calls the Example(int) constructor using the this keyword. This allows the Example() constructor to reuse the code in the Example(int) constructor and set the value member variable to a default value.

It's important to note that the this keyword must be the first statement in a constructor, and it can only be used to call another constructor in the same class.

Created Time:2017-10-17 20:18:52  Author:lautturi