java this 赋值,为什么java中不允许赋值给'this'?

The error I get from the compiler is "The left hand side of an assignment must be a variable". My use case is deep copying, but is not really relevant.

In C++, one can assign to *this.

The question is not how to circumvent assignment to this. It's very simple, but rather what rationale is there behind the decision not to make this a variable.

Are the reasons technical or conceptual?

My guess so far - the possibility of rebuilding an Object in a random method is error-prone (conceptual), but technically possible.

EDIT Please restrain from variations of "because java specs say so". I would like to know the reason for the decision

解决方案

In C++, one can assign to *this

Yes, but you can't do this = something in C++, which I actually believe is a closer match for what you're asking about on the Java side here.

[...] what rationale is there behind the decision not to make this a variable.

I would say clarity / readability.

this was chosen to be a reserved word, probably since it's not passed as an explicit argument to a method. Using it as an ordinary parameter and being able to reassign a new value to it, would mess up readability severely.

In fact, many people argue that you shouldn't change argument-variables at all, for this very reason.

Are the reasons technical or conceptual?

Mostly conceptual I would presume. A few technical quirks would arise though. If you could reassign a value to this, you could completely hide instance variables behind local variables for example.

My guess so far - the possibility of rebuilding an Object in a random method is error-prone (conceptual), but technically possible.

I'm not sure I understand this statement fully, but yes, error prone is probably the primary reason behind the decision to make it a keyword and not a variable.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值