This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Q- Which of the follwing are true? Choose 4 1 if a.equals(b) returns true;it imlpies a==b 2 if a.equals(b) returns true then b.equals(a) is also true 3 if a.equals(b) returns true it implies a.getClass()==b.getClass() 4 if a.equals(b) returns true & if b.equals(c) returns true then it implies a.equals(c) is also true 5 a.equals(null) returns false for any non=null refernce va;ue a 6 if a.equals(b) returns true it implies a.hashCode()==b.hashCode()
Ans is 2,4,5 & 6.
I understand why 2,4,5,6 are correct but i dont understand why 3rd is wrong.Because equals method returns false if object compared is of different type than the object on which it is called.So in that sense if a.equals(b) returns true then both a & b should be of the same class & getClass() method returns runtime name of the class. Somebody please tell me where i am going wrong???
As you may have guessed this is a bad question... it looks like the question is testing you on the requirements of the equals() methods, not what is actually happening. While it is true that most (if not all) implementations return false if the objects are of different types, this is actually not required.
Here is the excerpt from the JavaDoc...
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value x, x.equals(x) should return true. - It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. - It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. - It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. - For any non-null reference value x, x.equals(null) should return false.
Henry [ November 26, 2006: Message edited by: Henry Wong ]
hi Henry thanks for the reply I am still confused with this. I tried this example where i used references of two differnt classes
String s="sads"; Object ob=s; System.out.println(ob.equals(s)); >>>>> this will print true System.out.println(ob.getClass()==s.getClass());>>>>>this will print true
I guess this is because getClass() method compares classes of runtime objects.
i still dont understand how can two objects be equal() but still their getClass() will return false. If possibe can you explain me this with some example where equals() method will reurn true but getClass() will return false.