Java: Using “this” as an argument/parameter name of an instance method? [duplicate]

别等时光非礼了梦想. 提交于 2019-12-18 04:39:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39535995/java-using-this-as-an-argument-parameter-name-of-an-instance-method

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