Why can we use 'this' as an instance method parameter?

后端 未结 2 1223
别那么骄傲
别那么骄傲 2020-12-02 20:46

What is receiver parameter in Java ? Java 8 Language Specification talks about this.

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 21:26

    The JLS gives a hint:

    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.

    These two methods are equivalent:

    class Test {
        void m1() { }
        void m2(Test this) { }
    }
    

    However the latter allows you to add annotations:

    void m2(@MyAnnotation Test this) { }
    //where MyAnnotation can be defined like this for example:
    @Target(ElementType.TYPE_USE) @interface MyAnnotation {}
    

提交回复
热议问题