java - Eclipse这个自动生成的equals方法这句话是不是可以去掉?

查看:118
本文介绍了java - Eclipse这个自动生成的equals方法这句话是不是可以去掉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

问题

我用Eclipse自动生成了Student类的equals方法,发现下列代码中关于Student的强制转似乎是多余的,如果两个对象的字节码文件相同,那类型必然就是一样的啊,为啥还要强制转换呢?

萌新有困惑,求大神解惑,谢谢!

if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;

完整代码

package com.test.demo001;

public class Student{
    private String name;
    private int age;
    
    public Student() {

    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}




解决方案

你这个equal方法的参数是Object类型 就表示这个参数是可以传任何类型不限于Student
if (getClass() != obj.getClass())是判断你传入的参数是否是Student对象
你要从Object类型调用Student的属性 。。当然必须要强转语法是这么规定的。

这篇关于java - Eclipse这个自动生成的equals方法这句话是不是可以去掉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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