2

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?

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
Sid
  • 51
  • 4

5 Answers5

8

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
2

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.

mnagel
  • 6,729
  • 4
  • 31
  • 66
1

this is not a variable you can assign a value to. It is a built-in expression returning the object that is the context for the method currently executing.

While re-assigning this might be useful for some nice hacks, it would mess up all kind of things.

Thomas Stets
  • 3,015
  • 4
  • 17
  • 29
1

The this keyword is used to provide a reference to the current object within its class. Mostly, it is used to clarify scope issues with local variables which have the same identifier as a class member. E.g.

public void function (int param) {
   this.param = param   
}

Reassigning it to another object goes beyond the task assigned to the keyboard. What you want to do, (reassing a reference) can be achieved on the upper context, i.e. the context in which the object was created (and a reference to it was assigned).

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
0

Wrong thinking about this. this is just a keyword(not variable) in java which referenced to current instance and its a compilation restriction that keyword(any not only this) can not be initialized.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103