铸造等于方法 [英] Casting in equals method

查看:123
本文介绍了铸造等于方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在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 ,所以你必须强制它告诉编译器它是 Dog

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.

这篇关于铸造等于方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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