Last active
August 29, 2015 14:00
-
-
Save franklingu/9ecf7ec937c31f10e62e to your computer and use it in GitHub Desktop.
discussion about equals method in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Recently I have reading Effective Java and the following really | |
| took me some time to digest as it seems easy but tricky. | |
| Sample code is as the following: | |
| (!Attention: for simplicity, hashCode is not given here) | |
| ``` | |
| public class EqualsTest { | |
| public class Point { | |
| private int _x; | |
| private int _y; | |
| public Point(int x, int y) { | |
| this._x = x; | |
| this._y = y; | |
| } | |
| public int getX() { | |
| return this._x; | |
| } | |
| public int getY() { | |
| return this._y; | |
| } | |
| @Override | |
| public boolean equals(Object o) { | |
| if (!(o instanceof Point)) { | |
| return false; | |
| } | |
| Point another = (Point)o; | |
| return this._x == another.getX() && this._y == another.getY(); | |
| } | |
| } | |
| public class ColorPoint extends Point { | |
| private int _colorType; | |
| public ColorPoint(int x, int y, int colorType) { | |
| super(x, y); | |
| this._colorType = colorType; | |
| } | |
| public int getColorType() { | |
| return this._colorType; | |
| } | |
| @Override | |
| // this implementation will violate symmetry of equals method as a Point can be | |
| // equal to ColorPoint but ColorPoint will never be equal to Point | |
| // more explanation on this: Effective Java Item 8 | |
| public boolean equals(Object o) { | |
| if (!(o instanceof ColorPoint)) { | |
| return false; | |
| } | |
| ColorPoint another = (ColorPoint)o; | |
| return super.equals(o) && this._colorType == another.getColorType(); | |
| } | |
| } | |
| public static void main(String args[]) { | |
| EqualsTest t = new EqualsTest(); | |
| Point p = t.new Point(1, 2); | |
| ColorPoint cp = t.new ColorPoint(1, 2, 2); | |
| if (p.equals(cp)) { | |
| System.out.println("P is equal to cp"); | |
| } | |
| if (cp.equals(p)) { | |
| System.out.println("Cp is equal to p"); | |
| } | |
| } | |
| } | |
| ``` | |
| 1. reflexivity -- this one should be easy to get as this.equals(this) | |
| is not hard to ensure | |
| 2. symmetry -- the above example is for symmetry | |
| 3. transitivity -- the book illustrates this point. | |
| so the solution: composition instead of inheritance. |
Author
Author
return super.equals(o) && this._colorType == another.getColorType();
this line is doing what you are saying~
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I do not quite get you. So you want to return the result of super.equals directly(clearly this does not work)? If you do not want to return the result, what do you do with the result from super.equals? @wgx731