Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 367
Hari Krishna Avatar asked Jun 18 '14 16:06

Hari Krishna


People also ask

Why do we need to use the this keyword in our instance methods?

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 .

Can instance methods have parameters?

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.

How an instance method can be used?

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.

Why do we use this in Java?

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).


1 Answers

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 {} 
like image 144
assylias Avatar answered Sep 22 '22 23:09

assylias