Not able to pass reference variable of an object in actual argument in the case of using this as formal argument

Viewed 50

Here is the following code:

class Sample{

  private void display(Sample this, int x){
    System.out.println(x);
  }

  public static void main(String[] args) {
    Sample s = new Sample();
    s.display(10);
  }
}

The above code is working fine if I do not pass reference variable of Sample class as an actual argument i.e. s.display(10).

I am aware of the fact that from JDK 8 onwards we are allowed to pass this as parameter(formal arguments) and that too as the first argument and compiler internally inserts Sample this as first argument as parameter(or formal argument) i.e. private void display(Sample this..... if I do not write Sample this as pararemeter (formal argument) explicitly.

But if I try to pass reference variable as argument(actual argument) i.e. s.display(s, 10), then the code doesn't compile even when both the actual and formal arguments are same. eg:

class Sample{

  private void display(Sample this, int x){
    System.out.println(x);
  }

  public static void main(String[] args) {
    Sample s = new Sample();
    s.display(s, 10);
  }
}

What's the reason behind of not compiling the above code?

1 Answers

s.display(s, 10); doesn't compile because the compiler internally passes the this reference to s as well, that's why s.display(10) works - the compiler makes it to be similar to Sample.display(s, 10) while s.display(s, 10) would be more like Sample.display(s, s, 10).

Think of instance methods as being static methods which implicitly get the this formal parameter. Now try adding another method like static void display(Sample that, int x). Which one should be called when you're calling s.display(s, 10)? You might assume it's the instance method that takes this but it's actually the static method that's called (albeit the compiler would warn about a static method being accessed in a non-static way).

Additionally, what would happen if you were allowed to call display(Sample this, int x) as s.display(s, 10)? You could as well call s.display(new Sample(), 10) and now you'd have a conflict since this wouldn't refer to s anymore. That's why this is not allowed.

Related