【问题标题】:Using super() for equals() in a subclass in a different package在不同包的子类中将 super() 用于 equals()
【发布时间】:2013-01-25 08:42:07
【问题描述】:

我有一个类 Vehicle 位于包 A 中,一个类 Car 位于包 B 中,我想使用 equals 方法并通过使用 super() 来利用继承,但我不知道该怎么做.

当我尝试在 main 中运行文件时,我得到了这个:

Exception in thread "main" java.lang.NullPointerException
    at vehicle.Vehicle.equals(Vehicle.java:97)
    at car.Car.equals(Car.java:104)
    at Main.main(Main.java:48)

代码如下:

public boolean equals(Vehicle other) {
    if (this.type.equals(other.type)) {
        if (this.year == other.year && this.price == other.price) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
//equals in Car
public boolean equals(Car other) {
    if (this.type.equals(other.type)) {
        if (this.speed == other.speed && this.door == other.door) {
            if (super.equals(other)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

【问题讨论】:

  • 使用instanceof检查实例类型。
  • 请注意,您没有覆盖equals 方法,而是重载了它。 equals 方法接受 Object 作为参数。
  • @RohitJain 很好的指出。
  • 如果我使用 Object,equals() 方法不起作用,因为类车辆在包中,并且其变量具有默认访问权限,这意味着只有包中的类可以访问它。
  • @prog: 你能把VehicleCar 类的代码放上去吗?

标签: java inheritance compilation nullpointerexception package


【解决方案1】:

null 作为参数传递时,the contractequals() 方法应返回false

对于任何非空引用值xx.equals(null) 应返回false

在每个equals()方法的最开始添加这个:

if(other == null) {
  return false;
}

其次你必须覆盖equals(),而不是重载它:

public boolean equals(Object other)

最后,您需要 instanceof 和向下转换才能使这一切正常工作。

顺便说一句:

if (this.speed == other.speed && this.door == other.door)
{
    if(super.equals(other))
    {
        return true;
    }
    else
    {
        return false;
    }
}
else
{
    return false;
}

相当于:

if (this.speed == other.speed && this.door == other.door)
{
    return super.equals(other);
}
else
{
    return false;
}

这又可以简化为:

return this.speed == other.speed && this.door == other.door && super.equals(other);

【讨论】:

  • 经验法则:constant.equals(variable)。 +1
  • @Legend 并不是真正的经验法则,因为这有时可能是错误的
  • 我认为我得到null的原因是因为type是null,因为type在另一个包中并且它不是公共的,我无法访问它,因为访问权限是默认的。跨度>
  • 对象无权访问速度和门变量
  • @prog:确实,这就是为什么我说“你需要 instanceof 和向下转换才能使这一切正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多