28

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

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Hari Krishna
  • 3,658
  • 1
  • 36
  • 57
  • 5
    Just found it in http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1. It's unclear what the OP needs more than the JLS says though... any answer is likely to just reword that. – Jon Skeet Jun 18 '14 at 16:56
  • [From JLS](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1), is it a formal parameter? Or I'm misunderstanding it? – Christian Tapia Jun 18 '14 at 16:57
  • 3
    I'd say the question is pretty clear. – olovb Apr 25 '15 at 04:28

2 Answers2

39

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 {}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 4
    Another example is given in http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#d5e14278 where no enclosing instance of the outer type is available during construction – digital illusion Jan 14 '16 at 16:39
8

Receiver parameters allow to pass arguments and extract additional information from these arguments. The only purpose of writing the receiver explicitly is to make it possible to annotate the receiver’s type. Now, if you implement the AnnotatedElement interface, you could call the getAnnotation() method of your class to get an annotation type. For more information, you can read this.

mernst
  • 7,437
  • 30
  • 45
Debasis
  • 3,680
  • 1
  • 20
  • 23