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;
    }
}




阅读 3.6k
3 个回答

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

字节码文件一模一样,但是ClassLoader不同,也是不一样的。

虽然字节码是相同的, 但是你必须向下进行强制转型为 Student 类型, 你才能进行 other.age 或者 other.name 操作, 不能使用 obj.age 或者 obj.name , 入参的 obj 对象是父类, 不具有子类中的成员变量和方法.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题