Computer >> Computer tutorials >  >> Programming >> Java

Is it possible to assign a reference to this in java?


The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using it, you can refer the members of a class such as constructors, variables, and methods.

Is it possible to assign a reference to this in java?

Assigning reference to "this"

According to the definition "this" is a keyword which acts as a reference to the current object (the object from whose constructor/method you are using it), its value id is fixed. Therefore, you cannot assign a new reference value to it. Moreover, it is just a keyword, not a variable.

Still, if you try to it assign a reference value to "this" it leads to a compilation error.

Example

In the following Java program, the class (ExampleClass) has two private variables name, age and, a parameterized constructor which instantiates these variables. From a method named display, we are trying to assign a new value to "this".

public class ExampleClass {
   private String name;
   private int age;
   public ExampleClass(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void display(){
      this = new ExampleClass("krishna", 23);
   }
}

Compile-time error

On compiling, this program gives you an error as shown below −

ExampleClass.java:14: error: cannot assign a value to final variable this
      this = new ExampleClass("krishna", 23);
      ^
1 error