2

I found that the following code compiles (Java 8), despite a wrong number of arguments and a usage of reserved keyword 'this'.

public interface Comparable<T> {
    public int compareTo(T o);
}


public class Person implements Comparable<Person> {

    @Override
    public int compareTo(Person this, Person other) {
        return 0;
    }
}

What is the reason for such behavior? Any code examples are welcome.

Maxim Kirilov
  • 2,639
  • 24
  • 49
  • 1
    Did you define `Comparable` yourself? – OneCricketeer Nov 16 '17 at 17:20
  • `this` will always refer to the object that the method is attached to (the Person); you don't need to add a parameter for it. It looks like whatever you're trying to do is already done by java. – byxor Nov 16 '17 at 17:20
  • 1
    `method(ClassName this, other)` will be compiled same as `method(other)` if it belongs to `ClassName`. Some people (if I remember correctly coming from C++) like to explicitly add that parameter to show on which object it will be invoked. Possibly related: https://stackoverflow.com/a/44095738/1393766 – Pshemo Nov 16 '17 at 17:21
  • 1
    I just learned something new today. :) – OldCurmudgeon Nov 16 '17 at 17:24
  • It is useful if you want to add an annotation to the `this` variable. – Andy Turner Nov 16 '17 at 17:37
  • In which way? Can you give an example? – Maxim Kirilov Nov 16 '17 at 20:34

0 Answers0