Wednesday, December 30, 2009

Puzzle 74: Identity Crisis











 < Day Day Up > 







Puzzle 74: Identity Crisis



This 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:





public class Conundrum {

public static void main(String[] args) {

Enigma e = new Enigma();

System.out.println(e.equals(e));

}

}




Oh, and one more thing: You must not override equals.





Solution 74: Identity Crisis



At 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:





final class Enigma {

// Don't do this!

public boolean equals(Enigma other) {

return false;

}

}




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:





final class Enigma {

public Enigma() {

System.out.println(false);

System.exit(0);

}

}




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: