< Day Day Up > |
Puzzle 74: Identity CrisisThis program is incomplete. It lacks a declaration for Enigma, a class that extends java.lang.Object. Provide a declaration for Enigma that makes the program print false:
Oh, and one more thing: You must not override equals. Solution 74: Identity CrisisAt first glance, this may seem impossible. The Object.equals method tests for object identity, and the object passed to equals by Enigma is certainly the same as itself. If you can't override Object.equals, the main method must print TRue, right? Not so fast, cowboy. Although the puzzle forbids you to override Object.equals, you are permitted to overload it, which leads to the following solution:
Although this solves the puzzle, it is a very bad thing to do. It violates the advice of Puzzle 58: If two overloadings of the same method can be applied to some parameters, they should have identical behavior. In this case, e.equals(e) and e.equals((Object)e) return different results. The potential for confusion is obvious. There is, however, a solution that doesn't violate this advice:
Arguably, this solution violates the spirit of the puzzle: The println invocation that produces the desired output appears in the Enigma constructor, not the main method. Still, it does solve the puzzle, and you have to admit it's cute. As for the lesson, see the previous eight puzzles and Puzzle 58. If you do overload a method, make sure that all overloadings behave identically. |
< Day Day Up > |
No comments:
Post a Comment