我正在学习 Mooc 课程,它教我们如何比较像“人”这样的组合类中的对象,看看它们是否彼此相等。他们给了我们以下代码:
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the type of the compared object is not SimpleDate, the objects are not equal
if (!(compared instanceof SimpleDate)) {
return false;
}
// convert the Object type compared object
// into an SimpleDate type object called comparedSimpleDate
SimpleDate comparedSimpleDate = (SimpleDate) compared;
// if the values of the object variables are the same, the objects are equal
if (this.day == comparedSimpleDate.day &&
this.month == comparedSimpleDate.month &&
this.year == comparedSimpleDate.year) {
return true;
}
// otherwise the objects are not equal
return false;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
Run Code Online (Sandbox Code Playgroud)
}
对于 equals 方法,我知道它们首先使用 == 进行比较以检查它是否是相同的位置。接下来,他们查看比较对象是否与您正在比较的对象类型相同 - 如果不是,则返回 false。之后,他们将比较对象转换为您要比较的对象类型,然后比较其中的值。我的问题是,当比较对象是不同类型的对象时,您已经准备返回 false 时,转换比较对象有什么意义?没有
`SimpleDate comparedSimpleDate = (SimpleDate) compared;`
Run Code Online (Sandbox Code Playgroud)
似乎没有必要?
线是必要的。否则你不能访问它的数据和方法。
Java 不允许您这样做,compared.getYear()或者compared.year因为您只知道compared它是一个Object. 所以它可能是一个Cat没有getYear()方法的,编译器无法知道。
因此,您必须强制转换,这意味着“嘿编译器,相信我,我知道这实际上是一个SimpleDate,所以请允许我将其视为一个”。顺便说一句,如果它实际上不是SimpleDate.
当然,您检查过它实际上是 aSimpleDate之前,但是编译器不够聪明,无法连接点。它只知道那compared是类型Object。
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |