Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override and overload

Tags:

java

My question is: Why a4.equals(a2) causes method1 to execute and not method2? a2 points to AA and it is the parameter. And the same about a2.equals(b1). It seems that when it doesnt points to BB(to the class where all the equals methods are) it will cause only method1 to execute and it doesnt matter which type of parameter a method gets.

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));
    }
}
like image 899
Arthur Avatar asked Mar 11 '23 20:03

Arthur


1 Answers

The only equals method known to AA class is Object's equals, which accepts an Object argument. Therefore only public boolean equals(Object ob) can be called when calling a4.equals(a2) or a2.equals(b1), since the compile time type of both a2 and a4 is AA.

The method that gets called in run-time is your "method1", since it overrides Object's equals. The public boolean equals(AA ob) and public boolean equals(BB ob) overloads can only be called for references whose compile time type is BB, since method overloading is resolved based on the compile-time type of the object of which the method is called. If you call b1.equals() you will see your other methods being chosen, since method overloading will be used.

like image 59
Eran Avatar answered Mar 31 '23 03:03

Eran