0

I have the following code, the question is what equals function will be called? The answer is - the equals of an Object class, can someone explain why? I thought that the equals of A class will be called since in runtime a is A and A has a proper equals function for class A as b is a reference of class A. Why my assumption is wrong?

public class MainClass
{

  public static void main(String[] args)
  {

    Object a = new A();
    A b = new B();

    System.out.println(a.equals(b));

  }
}


public class A
{
    public boolean equals (A other)
    {
      System.out.println("a");
      return true;
    }
}

public class B extends A
{

    public boolean equals (Object other)
    {
      System.out.println("b");
      return true;
    }

    public boolean equals (B other)
    {
      System.out.println("c");
      return true;
    }
}
VitalyD
  • 289
  • 1
  • 15
  • 1
    only `.equals(Object o)` is visible through the `Object`-reference `a`. – Turing85 Jun 18 '18 at 15:03
  • 2
    @AmineMessaoudi That would end up in a compiler error. It is not an override, as the argument type is `A` , not Object. That is the whole point: A is **not** overriding Object.equals(). So I think you need to pay more attention when providing hints to other users. – GhostCat Jun 18 '18 at 15:07
  • @GhostCat you're right thanks – Amine Messaoudi Jun 18 '18 at 15:09
  • *The answer is - the equals of an Object class, can someone explain why?*, can you explain *Why it should be anything else?* that will answer your question for you. –  Jun 18 '18 at 15:11

0 Answers0