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

我们两清 提交于 2019-12-01 07:40:55

问题


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?


回答1:


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.




回答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.




回答3:


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.




回答4:


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).




回答5:


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.



来源:https://stackoverflow.com/questions/26293924/why-is-the-this-keyword-final-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!