Can you write a simple program that compares two objects to return if they are equal or not? This method will be handy in defining your own equals( ) method.

This is usefull in domain or value object class to compare different object fields in an equals method

public class DomainObject {

 

//protected because only inheriting domain classes can use it

protected boolean isPropertyEqual(Object compare1, Object compare2) {

// go here if compare1 is null, i.e. test cases 1 & 3

if (compare1 == null) {

if (compare2 != null) {

return false;

}

//go here if compare1 is not null, i.e. test cases 2 & 5

} else if (!compare1.equals(compare2)) {

return false;

}

 

return true;      //test cases 1 & 4

}

 

public static void main(String[] args) {

DomainObject d =  new DomainObject();

Print(d.isPropertyEqual(null, null));  //test case 1

Print(d.isPropertyEqual(“abc”, null)); //test case 2

Print(d.isPropertyEqual(null, “abc”)); //test case 3

Print(d.isPropertyEqual(“abc”, “abc”));//test case 4

Print(d.isPropertyEqual(“abc”, “cba”));//test case 5

}

 

public static void Print(boolean bol){

System.out.println(bol);

}

}

 

 

The above class must be abstract. It was not tagged abstract to demo via the main() method by creating a new DomainObject().

The above method can be used in an extending class like

public class Security extends DomainObject implements Serializable {

 

private String id;

//skipping other methods like getter/setter, toString, etc

 

public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (!(obj instanceof Security)) {

return false;

}

 

//calling super class handy method we just created

return isPropertyEqual(this.id, ((Security) obj).getId());

}

 

public int hashCode() {

return id.hashCode();

}

}