// // FINALLY, a correct, modular, and extensible solution // // plus it supplies a reasonable hashCode() implementation // along the guidelines of chapter 3 of "Effective Java" // class A { public int a; public A(int i) { a = i;} public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; return ((this.getClass() == o.getClass()) && (a == ((A) o).a)); } public int hashCode() { return 17 + a; } } class B extends A { public int b; public B(int i, int j) {super(i); b = j;} public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; return ((this.getClass() == o.getClass()) && (b == ((B) o).b) && (super.equals(o))); } public int hashCode() { return b + 37*super.hashCode(); } } class C extends B { public int c; public C(int i, int j, int k) {super(i,j); c = k;} public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; return ((this.getClass() == o.getClass()) && (c == ((C) o).c) && (super.equals(o))); } public int hashCode() { return c + 37*super.hashCode(); } } public class EqualsTest6 { public static void main(String[] args) { A a1 = new A(1); B b1 = new B(1,1); C c1 = new C(1,1,1); System.out.println("a1.equals(b1) = " + a1.equals(b1)); System.out.println("a1.equals(c1) = " + a1.equals(c1)); System.out.println("b1.equals(a1) = " + b1.equals(a1)); System.out.println("b1.equals(c1) = " + b1.equals(c1)); System.out.println("c1.equals(a1) = " + c1.equals(a1)); System.out.println("c1.equals(b1) = " + c1.equals(b1)); System.out.println("a1.equals(a1) = " + a1.equals(a1)); System.out.println("b1.equals(b1) = " + b1.equals(b1)); System.out.println("c1.equals(c1) = " + c1.equals(c1)); System.out.println("a1.equals(new A(1)) = " + a1.equals(new A(1))); System.out.println("b1.equals(new B(1,1)) = " + b1.equals(new B(1,1))); System.out.println("c1.equals(new C(1,1,1)) = " + c1.equals(new C(1,1,1))); System.out.println("c1.equals(null) = " + c1.equals(null)); System.out.println("a1.hashCode() = " + a1.hashCode()); System.out.println("(new A(1)).hashCode() = " + (new A(1)).hashCode()); System.out.println("b1.hashCode() = " + b1.hashCode()); System.out.println("(new B(1,1)).hashCode() = " + (new B(1,1)).hashCode()); System.out.println("c1.hashCode() = " + c1.hashCode()); System.out.println("(new C(1,1,1)).hashCode() = " + (new C(1,1,1)).hashCode()); } }