Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parameter confusion

In the code below why is it that o1.equals(o2); calls equals(Object o) not the equals(EqualsTest et) even though o1 and o2 are referencing objects of type EqualsTest!

public class EqualsTest {
      public static <T> boolean equalTest(T o1, T o2) {
          return o1.equals(o2);
      }
      public static void main(String[] args) {
          EqualsTest et1 = new EqualsTest();
          EqualsTest et2 = new EqualsTest();
          System.out.println(et1.equals(et2));
          System.out.println(equalTest(et1, et2));
      }
      public boolean equals(Object o) {
          if (o instanceof EqualsTest) {
              System.out.println("equals(Object)");
              return true;
          }
          return false;
      }
      public boolean equals(EqualsTest et) {
          System.out.println("equals(EqualsTest)");
          return this.equals((Object)et);
      }
}
like image 461
user133466 Avatar asked Dec 21 '25 16:12

user133466


1 Answers

The compiler finds the corresponding method based on the declared type of the argument, not the most specific one. Since you didn't specify anything for thee T, it defaults to Object, as @nicholas.hauschild correctly points out.

like image 127
Volker Stolz Avatar answered Dec 23 '25 06:12

Volker Stolz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!