Why is it possible to compare to objects with equals and it compiles and when I compare them with "==" there is a compiler error "incompatible types". Why does "==" perform a types check and equals doesn't? class Employee {} class ObjectTest1c { public static void main ( String args [ ] ) { Integer ar1 = new Integer(1); Employee emp = new Employee();
compiler tries to convert operand type before comparison when u use == operator.equals() also do the conversion.but here this converts to Object type.since Object is super class all the objects can convert to Object type.
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9001
posted
0
A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion Java Language Specification
The method equals defines a notion of object equality, which is based on value, not reference, comparison. Java Language Specification myClassObject.equals( yourClassObject ) does not depend on whether myClassObject and yourClassObject are objects of the same class. But they must both be Objects (not primitives).
For example, a date object of the java.sql.Date may be equal to a date object of the java.util.Date class if they are both the same date even though the dates were instantiated from different classes.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
karl koch
Ranch Hand
Joined: May 25, 2001
Posts: 388
posted
0
hi the == is used to compare two references, that is if two references point to the sae object. the equals() method (inherited from java.lang.Object) checks if two objects have the same content.
k
Mark Mokris
Ranch Hand
Joined: May 08, 2002
Posts: 61
posted
0
A related question... Don't you have to override the equals() method in any classes that you the programmer create in order to "define" your own notion of equality? The default behavior of equals( ), inherited from Object, still just compares object references, doesn't it?