Appendix A Answers to Review Questions
Chapter 1: Advanced Class Design
- A. Based on the
equals()
method in the code, objects are equal if they have the sameemployeeId
. ThehashCode()
method correctly overrides the one fromObject
. Theequals()
method is an overload of the one fromObject
and not an override. It would be better to passObject
since an override would be better to use here. It is odd to overridehashCode()
and notequals()
. - A.
hashCode()
is correct and perfectly reasonable given thatequals()
also checks that field.ClassCastException
is a runtime exception and therefore does not need to be handled or declared. The override inequals()
is correct. It is common forequals()
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. - 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
overridesequals()
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. - C. The
equals()
method is correct. You are allowed to use any business logic that you want in determining equality. ThehashCode()
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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.