Appendix A Answers to Review Questions

Chapter 1: Advanced Class Design

  1. A. Based on the equals() method in the code, objects are equal if they have the same employeeId. The hashCode() method correctly overrides the one from Object. The equals() method is an overload of the one from Object and not an override. It would be better to pass Object since an override would be better to use here. It is odd to override hashCode() and not equals().
  2. A. hashCode() is correct and perfectly reasonable given that equals() also checks that field. ClassCastException is a runtime exception and therefore does not need to be handled or declared. The override in equals() is correct. It is common for equals() to refer to a private instance variable. This is legal because it is within the same class, even if it is referring to a different object of the same class.
  3. C. s1 points to the string pool. s2 points to an object on the heap, since it is created at runtime. == checks for reference equality. These are different references, making B incorrect. String overrides equals() so the actual values are the same, making C correct. And yes, this question could have appeared on the OCA. Remember that the OCP is cumulative. A question may appear to be about one thing and actually be about a simpler concept.
  4. C. The equals() method is correct. You are allowed to use any business logic that you want in determining equality. The hashCode() method is not correct. It violates the rule that two objects that return ...

Get OCP Oracle® Certified Professional Java® SE 8 Programmer II now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.