为什么“& this&"Java中的关键字final? [英] Why is the "this" keyword final in Java?

查看:71
本文介绍了为什么“& this&"Java中的关键字final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎几乎没有人意识到这一点,但是Java中的"this reference"是最终的.在正常的编程天中,我认为我可以通过在自己的类中重新定义此引用来重新定义整个实例:

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
}

为什么这个引用在Java中是最终的?

Why the this reference is final in Java?

推荐答案

问题不是不是 this final 的引用-本身根本不是引用. this keyword ,它表示一个值,该值是对为其调用实例方法或默认方法的对象的引用"(JLS§15.8.3).

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

此外,从可以重新分配变量的意义上讲,重新分配它没有意义.请记住,重新分配引用只会更改该引用,而不会更改其他可能指向同一对象的引用.因此,重新分配 this 不仅是疯狂的,而且是无用的.

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.

这篇关于为什么“& this&"Java中的关键字final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆