I was solving some questions for my OCA prepration. I found this problem at Oracle's website listing sample questions for exam.
Code:
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;
}
}
Question:
What is the result?
- The output is "true" and MyStuff fulfills the Object.equals() contract.
- The output is "false" and MyStuff fulfills the Object.equals() contract.
- The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
- The output is "false" and MyStuff does NOT fulfill the Object.equals() contract.
- Compilation fails.
- An exception is thrown at run time.
Answer is-
3. The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
I understand how, and why the output is true
, but what I am not getting is that How come it does not fullfill the Object.equals()
contract, and what exactly is a "Contract" in Java, and what if we don't abide by it?