Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the "this" keyword final in Java? [duplicate]

Tags:

java

final

It seems a thing that almost no one has realized, but the "this reference" in Java is final. In a normal programming day I thought I could redefine the entire instance by redefining the this reference inside the own class:

public void method() {
    this = new MyObject("arg1", arg2, arg3); //it throws a compile error
}

Why the this reference is final in Java?

like image 389
Sid Avatar asked May 07 '26 20:05

Sid


2 Answers

The problem is not that this is a final reference - it's not itself a reference at all. this is a keyword that "denotes a value that is a reference to the object for which the instance method or default method was invoked" (JLS §15.8.3).

Furthermore, it wouldn't make sense to reassign it in the sense that a variable can be reassigned. Remember that reassigning a reference changes only that reference, and not other references that might point to the same object. So reassigning this would not only be insane but also useless.

like image 136
Paul Bellora Avatar answered May 09 '26 11:05

Paul Bellora


I find this question interesting from a theoretical point of view.

From a technical point of view this cannot work, as in Java we have pass-refererence-by-value ( http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html ) and cannot swap out objects where some other parts of code hold a reference to that object -- i.e. a true swap method is not possible in Java (see the linked article).

While you could theoretically reassign this, all other references to the object would not change and make the operation pretty senseless.

The closest thing you can achieve is a copy constructor.

like image 42
mnagel Avatar answered May 09 '26 10:05

mnagel