【发布时间】: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: 你能把
Vehicle和Car类的代码放上去吗?
标签: java inheritance compilation nullpointerexception package