微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在覆盖 equals() 方法时进行向下转换的目的是什么

如何解决在覆盖 equals() 方法时进行向下转换的目的是什么

我是 Java 新手,我已经理解了向上转型和向下转型的概念,但我无法理解他们为什么在这个被覆盖的 [Pet p1 = (Pet)obj] 方法中使用向下转型 (equals()):>

class Pet {
    String name;
    int age;
    String breed;

    Pet(String name,int age,String breed) {
        this.name = name;
        this.age = age;
        this.breed = breed;
    }

    @Override
    public boolean equals(Object obj) {
        // checking if the two objects
        // pointing to same object
        if (this == obj)
            return true;
        // checking for two condition:
        // 1) object is pointing to null
        // 2) if the objects belong to
        // same class or not
        if (obj == null
                || this.getClass() != obj.getClass())
            return false;
        Pet p1 = (Pet) obj; // type casting object to the
        // intended class type
        // checking if the two
        // objects share all the same values
        return this.name.equals(p1.name)
                && this.age == p1.age
                && this.breed.equals(p1.breed);
    }
}

public class GFG {
    public static void main(String args[]) {
        Pet dog1 = new Pet("SNow",3,"German Shepherd");
        Pet cat = new Pet("Jack",2,"Tabby");
        Pet dog2 = new Pet("SNow","German Shepherd");
        System.out.println(dog1.equals(dog2));
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。