2

I recently heard that it is possible since Java 8 to define an explicit parameter called this in instance methods, like this:

public class Test
{
    public void test(Test this, int i) { System.out.println(i); }
}

What is the use for this kind of syntax?

As you can clearly see in this screenshot (Eclipse, compiler compliance Java 8), this is valid syntax.

Proof

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
  • What would be the purpose of such declaration? – Tagir Valeev Jun 16 '15 at 15:44
  • Just as a sidenote: internally the compiler will change all instance methods to have a _this_ parameter but that's just how methods are enabled to operate on instances. That's something the compiler will do implicitly and not a developer explicitly. If developers where allowed to do that as well, they'd probably break the compiler. – Thomas Jun 16 '15 at 15:48
  • As you might be able to tell, that image is from the source code of a compiler, so I already know how `this` and instance methods work on the JVM. That is why the syntax makes sense, since `this`, the 0th parameter, is now explicit. – Clashsoft Jun 16 '15 at 15:52
  • When trying this in Eclipse Luna with Java 7, I get an error: _Explicit declaration of 'this' parameter is allowed only at source level 1.8 or above_. Indeed it seems that this is possible. – Dragan Bozanovic Jun 16 '15 at 15:55
  • This code will not compile, error ` expected` – MaxZoom Jun 16 '15 at 15:57
  • 3
    It's called a receiver. It's specified in JLS 8, [here](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1-220) (scroll up for syntax). – Sotirios Delimanolis Jun 16 '15 at 16:01
  • @MaxZoom you need to use Java 8 for this to work. – Clashsoft Jun 16 '15 at 16:02

1 Answers1

7

For Java 7 or prior, you cannot use this as name of a variable because it's a reserved keyword. What you can do is to pass this as parameter into a method:

class Test {
    public void foo(Test test, int i) {
        //...
    }
    public void foo(int i) {
        foo(this, i);
    }
}

For Java 8, refer to Why can we use 'this' as an instance method parameter?

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332