001package subclass.equals; 002class C1 { 003 int i; 004 public C1(int i) { this.i = i; } 005 public boolean equals(Object thatObject) { 006 if (!(thatObject instanceof C1)) 007 return false; 008 C1 that = (C1) thatObject; 009 return that.i == this.i; 010 } 011} 012class D1 extends C1 { 013 int j; 014 public D1(int i, int j) { super(i); this.j = j; } 015 public boolean equals(Object thatObject) { 016 if (!(thatObject instanceof D1)) 017 return false; 018 D1 that = (D1) thatObject; 019 return that.i == this.i && that.j == this.j; 020 } 021} 022class C2 { 023 int i; 024 public C2(int i) { this.i = i; } 025 public boolean equals(Object thatObject) { 026 if ((thatObject == null) || (thatObject.getClass() != this.getClass())) 027 return false; 028 C2 that = (C2) thatObject; 029 return that.i == this.i; 030 } 031} 032class D2 extends C2{ 033 int j; 034 public D2(int i, int j) { super(i); this.j = j; } 035 public boolean equals(Object thatObject) { 036 if ((thatObject == null) || (thatObject.getClass() != this.getClass())) 037 return false; 038 D2 that = (D2) thatObject; 039 return that.i == this.i && that.j == this.j; 040 } 041} 042public class Main { 043 public static void main(String[] args) { 044 C1 x1 = new C1(27); 045 C1 y1 = new D1(27,42); 046 System.out.println("x1==y1? " + (x1.equals(y1) ? "true" : "false")); 047 System.out.println("y1==x1? " + (y1.equals(x1) ? "true" : "false")); 048 049 C2 x2 = new C2(27); 050 C2 y2 = new D2(27,42); 051 System.out.println("x2==y2? " + (x2.equals(y2) ? "true" : "false")); 052 System.out.println("y2==x2? " + (y2.equals(x2) ? "true" : "false")); 053 } 054}