Can we assign the reference to this variable?

Category: JavaCan we assign the reference to this variable?
Editor">Editor Staff asked 2 years ago

Can we assign the reference to this variable?

1 Answers
Editor">Editor Staff answered 2 years ago

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be
shown. Consider the following example.
public class Test
{
public Test()
{
this = null;
System.out.println(“Test class constructor called”);
}
public static void main (String args[])
{
Test t = new Test();
}
}
Output
Test.java:5: error: cannot assign a value to final variable this
this = null;
^
1 error