java this参数,Java:使用“this”作为实例方法的参数/参数名称?

Recently from this question I have learned that the following appears to be legal java:

class Bar {

void foo(Bar this) {}

}

Now, I have tried to find where in the java standard it says that you are allowed to do this, and looked here but I couldn't find the section.

Can someone quote where it allows this form of method declaration and what the restrictions of declaring an argument named this are?

解决方案

It is valid with 1.8 or above JDK versions.

And here is the JLS saying that

The receiver parameter is an optional syntactic device for an instance method or an inner class's constructor. For an instance method, the receiver parameter represents the object for which the method is invoked. For an inner class's constructor, the receiver parameter represents the immediately enclosing instance of the newly constructed object. Either way, the receiver parameter exists solely to allow the type of the represented object to be denoted in source code, so that the type may be annotated.

If you read full bullet points you find the below imp notes,

Where a receiver parameter is allowed, its type and name are specified as follows:

In an instance method, the type of the receiver parameter must be the

class or interface in which the method is declared, and the name of

the receiver parameter must be this; otherwise, a compile-time error

occurs.

In an inner class's constructor, the type of the receiver parameter

must be the class or interface which is the immediately enclosing

type declaration of the inner class, and the name of the receiver

parameter must be Identifier . this where Identifier is the simple

name of the class or interface which is the immediately enclosing

type declaration of the inner class; otherwise, a compile-time error

occurs.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值