I've read this article: How to Write an Equality Method in Java.Basically, it provides a solution for an equals() method that supports inheritance:Point2D twoD   = new Point2D(10, 20);Point3D threeD = new Point3D(10, 20, 50);twoD.equals(threeD); // truethreeD.equals(twoD); // trueBut is it a good idea? these two instances appears to be equal but may have two different hash codes. Isn't that a bit wrong?I believe this would be better achieved by casting the operands instead.
Could an instance be equal to some other instance of a more specific type?
java;c#;scala;comparison
This should not be equality because it breaks transitivity. Consider these two expressions:new Point3D(10, 20, 50).equals(new Point2D(10, 20)) // truenew Point2D(10, 20).equals(new Point3D(10, 20, 60)) // trueSince equality is transitive, this should mean that the following expression is also true:new Point3D(10, 20, 50).equals(new Point3D(10, 20, 60))But of course - it isn't.So, your idea of casting is correct - expect that in Java, casting simply means casting the type of the reference. What you really want here is a conversion method that'll create a new Point2D object from a Point3D object. This would also make the expression more meaningful:twoD.equals(threeD.projectXY())