在 equals 方法中进行转换 [英] Casting in equals method

查看:28
本文介绍了在 equals 方法中进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在 Java 中覆盖 equals 方法的问题.在我的书中,我有以下示例:

I have a question about overriding the equals method in Java. In my book, I have the following example:

public class Dog{
     private String name;
     private int age;

public boolean equals(Object obj) {
    if(!(obj instanceof Dog)) return false;
    Dog other = (Dog) obj;                    ---> confused here
    if(this.name.equals(other.name) && (this.age == other.age) {
     return true;
    }
    else {
     return false;
    }
  }
}

我不明白为什么必须将引用强制转换为 Dog 引用.如果该引用不是 Dog 类型,我们将返回 false.为什么要投射它那么麻烦?

I don't understand why why have to cast the reference to the Dog reference. If that reference is not of type Dog we return false. Why all the hassle with casting it ?

推荐答案

obj 的声明类型是 Object,所以你必须强制转换它来告诉编译器它是一只.

The declared type of obj is Object, so you must cast it to tell the compiler that it is a Dog.

虽然逻辑上它不能是代码中的任何其他东西,但编译器对逻辑一无所知——它只知道类型.

Although logically it can't be anything else at that point in the code, the compiler doesn't know anything about logic - it only knows about the type.

这篇关于在 equals 方法中进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆