11. public class Test
22. {
33. private int num;
44. private String data;
55.
66. public boolean equals(Object obj)
77. {
88. if(this == obj)
99. return true;
1010. if((obj == null) || (obj.getClass() != this.getClass()))
1111. return false;
1212. // object must be Test at this point
1313. Test test = (Test)obj;
1414. return num == test.num &&
1515. (data == test.data || (data != null && data.equals(test.data)));
1616. }
1726. // other methods
1827. }
1class Complex {
2
3 private double re, im;
4
5 public Complex(double re, double im) {
6 this.re = re;
7 this.im = im;
8 }
9
10 // Overriding equals() to compare two Complex objects
11 @Override
12 public boolean equals(Object o) {
13
14 // If the object is compared with itself then return true
15 if (o == this) {
16 return true;
17 }
18
19 /* Check if o is an instance of Complex or not
20 "null instanceof [type]" also returns false */
21 if (!(o instanceof Complex)) {
22 return false;
23 }
24
25 // typecast o to Complex so that we can compare data members
26 Complex c = (Complex) o;
27
28 // Compare the data members and return accordingly
29 return Double.compare(re, c.re) == 0
30 && Double.compare(im, c.im) == 0;
31 }
32}
33
34// Driver class to test the Complex class
35public class Main {
36
37 public static void main(String[] args) {
38 Complex c1 = new Complex(10, 15);
39 Complex c2 = new Complex(10, 15);
40 if (c1.equals(c2)) {
41 System.out.println("Equal ");
42 } else {
43 System.out.println("Not Equal ");
44 }
45 }
46}
47