gpt4 book ai didi

java - 在此示例中,为什么即使在调用 getClass() 之后仍然需要对对象进行类型转换以确定其类型?

转载 作者:行者123 更新时间:2023-12-01 16:51:15 25 4
gpt4 key购买 nike

我正在关注this MOOC on OOP in Java它提出了 an example I don't fully understand 。在示例中,已创建一个 Book 类,并且他们正在为 Book 类构造一个“equals”重写方法。新的 equals() 方法接受任何对象的参数。如果该参数是与此 Book 对象具有相同名称和发布年份的 Book 对象,则返回 true。因为参数对象可以是Object类的任意对象,在调用getPublishingYear()getName()方法之前,如果调用的对象不是在 Book 类中,equals() 方法检查以确保它确实通过以下代码处理 Book 对象:

 if (getClass() != object.getClass()) {
return false;
}

我想就这么多了。我不明白的是,为什么在上面的代码之后,他们将参数对象转换为 Book ,然后调用 getPublishingYear()getName() 在新类型转换的对象而不是原始对象上:

Book compared = (Book) object;

if (this.publishingYear != compared.getPublishingYear()) {
return false;
}

if (this.name == null || !this.name.equals(compared.getName())) {
return false;
}

return true;

我不明白为什么这个步骤是必要的,因为如果由于上面的 getClass() 检查而对象不是 Book 类型,那么该方法应该已经返回 false。我尝试在没有这个额外转换步骤的情况下进行编译,发现该步骤确实是必要的 - 编译器在 getPublishingYear()getName() 上给出“找不到符号”错误,如果您不包括此步骤。那么我错过了什么?

equals() 方法完整:

@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
System.out.println(getClass());
if (getClass() != object.getClass()) {
return false;
}

Book compared = (Book) object;

if (this.publishingYear != compared.getPublishingYear()) {
return false;
}

if (this.name == null || !this.name.equals(compared.getName())) {
return false;
}

return true;
}

最佳答案

因为编译器无法(禁止)推断出您之前的类型检查是为了在转换之前消除不正确的对象类型而完成的。
例如,有时少即是多:如果在接下来的语句中您只需要将您的对象转换为基类或实现的接口(interface)之一?

interface Authored {
public getAuthorName();
}

interface Publication {
public String getISBN();
};

public class Book
implements Authored, Publication {

// ...
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
// on purpose, we use only the Publication interface
// because we want to avoid potential misspelling or missing
// title, author name, etc. impacting on equality check
// We'll consider ISBN as a key unique enough to
// determine if two books (e.g. registered in different
// libraries) are the same
Publication p=(Publication)other;
return this.getISBN().equals(p.getISBN());
}
}

关于java - 在此示例中,为什么即使在调用 getClass() 之后仍然需要对对象进行类型转换以确定其类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com