Java 8 Explicit 'this' Parameter

1.1k Views Asked by At

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

1

There are 1 best solutions below

2
On

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?