What is a receiver parameter in Java ? Java 8 Language Specification talks about this
.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
Things an object does are its methods (behavior). Methods can use instance variables so that objects of the same type can behave differently. A method can have parameters, which means you can pass one or more values in to the method.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With