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.