Page 1 of 1

OCAJP SE 7 - Question - Fulfills the contract?

Posted: Sat Jun 08, 2013 11:43 pm
by nickeasyuptech
I am preparing for OCAJP SE 7 and have a question. I have read several books and am using the Enthuware Mock Exams (which are great!) but haven't seen this phrase used yet. Any help is much appreciated!

What does it mean to 'fulfill the Object.equals() contract.'?

Below, please find a sample question using this phrase provided on Oracle's website at

http://education.oracle.com/pls/web_pro ... =SQ1Z0_803


The answer is 'C'

2. Given:

Code: Select all

public class MyStuff {
MyStuff(String n) { name = n; }
String name;
public static void main(String[] args) {
MyStuff m1 = new MyStuff("guitar");
MyStuff m2 = new MyStuff("tv");
System.out.println(m2.equals(m1));
}
public boolean equals(Object o) {
MyStuff m = (MyStuff) o;
if(m.name != null)
return true;
return false;
}
}
The answer is 'C'

What is the result?
A) The output is "true" and MyStuff fulfills the Object.equals() contract.
B) The output is "false" and MyStuff fulfills the Object.equals() contract.
C) The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
D) The output is "false" and MyStuff does NOT fulfill the Object.equals() contract
E) Compilation fails

Re: OCAJP SE 7 - Question - Fulfills the contract?

Posted: Sun Jun 09, 2013 6:13 am
by admin
The equals and hashCode method of a class are related by a contract which says that if the a.equals(b) returns true then a.hashCode() and b.hashCode() must also be same. So fulfilling the contract means that if you override any of these methods, you need to make sure that you still satisfy the above rule.

This is an important concept and I would suggest you to read more about it to understand completely.
-Paul.

Re: OCAJP SE 7 - Question - Fulfills the contract?

Posted: Sun Jun 09, 2013 12:12 pm
by nickeasyuptech
Thanks Paul, that makes sense now! I appreciate your help and will definitely be using and recommending your Mock Exams for any certification.