For a long time I have been struggling with the concept of static and dynamic binding. Each time that I would assume that I have understood the paradigm, I would come across a problem or code sample which would prove that I was wrong. Until today when I stumbled across this article which explained it a little too well.
To cut the chase, here is the deal. Overloaded methods are bound statically while Java uses dynamic binding for overridden ones.
So while this code:-
public boolean equals( Object other ) {
System.out.println( “Inside of Test.equals” );
return false;
}
public static void main( String [] args ) {
Object t1 = new Test();
Object t2 = new Test();
Test t3 = new Test();
Object o1 = new Object();
int count = 0;
System.out.println( count++ );// prints 0
t1.equals( t2 ) ;
System.out.println( count++ );// prints 1
t1.equals( t3 );
System.out.println( count++ );// prints 2
t3.equals( o1 );
System.out.println( count++ );// prints 3
t3.equals(t3);
System.out.println( count++ );// prints 4
t3.equals(t2);
}
would print
0
Inside of Test.equals
1
Inside of Test.equals
2
Inside of Test.equals
3
Inside of Test.equals
4
Inside of Test.equals
If you change the equals method to :-
public boolean equals( Test other ) {
System.out.println( “Inside of Test.equals” );
return false;
}
i.e. make it overloaded instead of overridden it would print:-
0
1
2
3
Inside of Test.equals
4
Problem solved!!!!!