Override and Overload

My question is: Why a4.equals(a2)calls method1to execute, and not method2? a2points to AA, and this is a parameter. And the same thing about a2.equals(b1). It seems that when it does not point to BB(the class where all the methods are equals), it will only lead to execution only method1, and it does not matter what type of parameter the method receives.

public class AA
{
    public int getVal()
    {
       return 5;
    }
}

public class BB extends AA
{
    private String _st = "bb";

    public boolean equals(Object ob)  //method1
    {
      System.out.println("Method 1");
        if((ob != null) && (ob instanceof BB))
        {
            if(_st.equals(((BB)ob)._st) && (getVal() == ((BB)ob).getVal()))
                return true;
        }
        return false;
    }


    public boolean equals(AA ob)  //method2
    {
    System.out.println("Method 2");
        if((ob != null) && (ob instanceof BB))
        {
            if(_st.equals(((BB)ob)._st) && (getVal() == ((BB)ob).getVal()))
            return true;
        }
        return false;
    }

    public boolean equals(BB ob)  //method3
    {
        System.out.println("Method 3");
        if(ob != null)
            if(_st.equals(((BB)ob)._st) && (getVal() == ((BB)ob).getVal()))
                return true;

        return false;
    }
}

public class Driver
{
    public static void main(String[] args)
    {
        AA a2 = new BB();
        AA a4 = new BB();   
        BB b1 = new BB();  

        System.out.println(a4.equals(a2));
        System.out.println(a2.equals(b1));
    }
}
+4
source share
1 answer

The only equalsmethod known to the class AAis Object equalsthat which takes an argument Object. Therefore, when you call a4.equals(a2)or a2.equals(b1)you can only call public boolean equals(Object ob), since the type of compilation time is both equal a2and a4equal AA.

, , "method1", Object equals. public boolean equals(AA ob) public boolean equals(BB ob) , BB, , . b1.equals(), , , .

+7

Source: https://habr.com/ru/post/1658773/


All Articles