Let's say that we have the following code
class TestEqual{
public boolean equals(TestEqual other ) {
System.out.println( "In equals from TestEqual" ); return false;
}
public static void main( String [] args ) {
Object t1 = new TestEqual(), t2 = new TestEqual();
TestEqual t3 = new TestEqual();
Object o1 = new Object();
int count = 0;
System.out.println( count++ );// shows 0
t1.equals( t2 ) ;
System.out.println( count++ );// shows 1
t1.equals( t3 );
System.out.println( count++ );// shows 2
t3.equals( o1 );
System.out.println( count++ );// shows 3
t3.equals(t3);
System.out.println( count++ );// shows 4
t3.equals(t2);
}
}
Basically, in the TestEqual class (that of course, extends Object) we have a method that is overloading the equals method from Object.
Also, we have some variables: Object t1, t2 instanced as TestEqual, TestEqual t3 instanced as TestEqual and an Object o1 instanced as an Object.
If we run the program, this will be the output.
0
1
2
3
In equals from TestEqual
4
This example seems a bit more complicated than the usual Car c = new Vehicle(); c.drive(); because the object from where we call the method is instanced different from its type, and also the parameter of the method is instanced different than its type.
I would like to check if I understood correctly what happens when we call each method, step-by-step regarding binding.
show 0
t1.equals(t2)
show 1
t1 is considered as a TestEqual object. The method equals is overloaded, so the binding is static, this means that we will pass t2 as an Object, so it will call the equals method inherited from the Object superclass, so it will not show any text.
show 1
t1.equals(t3)
show 2
This seems a bit weird. I would have expected to show "In equals from TestEqual", because t3 is a TestEqual object, so the equals from t1 should be called. My explanation here would be that t1 is static bound and considered as an Object, so the method equals inherited from the Object class is called, the parameter TestEqual t3 being upcast to Object. But wouldn't this mean that the previous explanation from t1.equals(t2) is wrong?
show 2
t3.equals(o1);
show 3
t3 is a TestEqual object, the parameter o1 is an Object, so the equals method inherited from Object is called, thus nothing is printed.
show 3
t3.equals(t3)
show 4
t3 is a TestEqual object, the parameter is a TestEqual object, so the overloaded method from TestEqual will be called, printing "In equals from TestEqual".
show 4
t3.equals(t2)
t3 is a TestEqual object, the parameter is an Object due to static binding (overloaded method), so the equal method inherited from Object is called, printing nothing.