fork download
  1. class Point {
  2. protected int x, y;
  3.  
  4. public boolean equals(Object o) {
  5. if (!(o instanceof Point)) return false;
  6. Point other = (Point)o;
  7. return other.x == x && other.y == y;
  8. }
  9.  
  10. public int hashCode() {
  11. return x * 31 + y;
  12. }
  13. }
  14.  
  15. class ColoredPoint extends Point {
  16. protected int color;
  17.  
  18. public boolean equals(Object o) {
  19. if (!(o instanceof ColoredPoint)) return false;
  20. ColoredPoint cp = (ColoredPoint) o;
  21. return super.equals(o) && cp.color == color;
  22. }
  23.  
  24. public int hashCode() {
  25. return super.hashCode() * 31 + color;
  26. }
  27. }
  28.  
  29. class BuggyInit {
  30. public static void main (String[] args) {
  31. Point center = new Point();
  32. ColoredPoint white = new ColoredPoint();
  33. ColoredPoint red = new ColoredPoint();
  34. red.color = 0xff0000;
  35.  
  36. System.out.println("center == white ? " + center.equals(white));
  37. System.out.println("center == red ? " + center.equals(red));
  38. System.out.println("Well, center == white, center == red, so, white == red, isn't it ? " + white.equals(red));
  39. System.out.println("Hm... center == white, so white == center, I'm sure. " + white.equals(center));
  40. }
  41. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
center == white ? true
center == red ? true
Well, cented == white, center == red, so, white == red, isn't it ? false
Hm... center == white, so white == center, I'm sure.  false