Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java equals方法的良好设计_Java - Fatal编程技术网

Java equals方法的良好设计

Java equals方法的良好设计,java,Java,我看到了: // Returns whether o refers to a Point object with // the same (x, y) coordinates as this Point object public boolean equals(Object o) { if (o instanceof Point) { Point other = (Point) o; return x == other.x && y

我看到了:

// Returns whether o refers to a Point object with  
// the same (x, y) coordinates as this Point object 
public boolean equals(Object o) {
    if (o instanceof Point) {
        Point other = (Point) o;
        return x == other.x && y == other.y;
    } else {
        return false;
    } 
}

为什么要求equals方法的参数取一个
对象不更明智(也更简单)。然后,如果我们试图比较一个点和一个非点,那么编译器将捕获它。这不是更好吗?

因为这样它就不会重写,这是许多标准库算法用于检查两个对象相等性的方法


这些算法中有许多可以在不同类型的对象上运行,这使得
equals
有必要将您的对象与任何其他类中的一个进行比较。

因为这打破了覆盖的第一条规则,并成为
equals()的重载
对象的方法类

方法重写规则:

  • 参数列表应与 重写的方法。
  • 返回类型应与返回类型相同或是返回类型的子类型 在超类中的原始重写方法中声明
  • 访问级别的限制不能比重写的更严格 方法的访问级别。例如:如果超类方法是 声明为public,则子类中的重写方法无法 要么是私人的,要么是受保护的
  • 仅当实例方法由 子类
  • 无法重写声明为final的方法
  • 声明为静态的方法不能被重写,但可以重新声明
  • 如果无法继承方法,则无法重写该方法
  • 与实例的超类位于同一包中的子类可以 重写任何未声明为private或final的超类方法
  • 不同包中的子类只能重写非final 方法声明为公共或受保护

您可以在Apache Commons库中简单地使用EqualBuilder类。

会是

public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}

重复:好的观点。这是Liskov替代原理的另一个版本吗?()
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}