Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created September 29, 2014 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/7bb8767d39950c7d3282 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/7bb8767d39950c7d3282 to your computer and use it in GitHub Desktop.
Equals / HashCode / ToString template
import java.util.Objects;
/*
* When defining equals, hashCode should be defined too.
* It is the civil thing to define toString too.
*/
class Base {
public String a = "a";
@Override
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (getClass() != obj.getClass()) { return false; }
Base other = (Base) obj;
return Objects.equals(this.a, other.a);
}
@Override
public int hashCode() {
return Objects.hash(this.a);
}
@Override
public String toString() {
return getClass().getName() + "[a=" + a + "]";
}
}
class Super extends Base {
public String b = "b";
@Override
public boolean equals(Object obj) {
if (! super.equals(obj)) { return false; }
Super other = (Super) obj;
return Objects.equals(this.b, other.b);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), this.b);
}
@Override
public String toString() {
return super.toString() + "[b=" + b + "]";
}
}
public class Sandbox {
public static void main(String[] args) {
Base b = new Base();
Super s = new Super();
System.out.println(b);
System.out.println(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment