为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2019-03-01 10:36:18
问题 我用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 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

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

查看完整回答
反对 回复 2019-03-01
?
LEATH

TA贡献1936条经验 获得超7个赞

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

查看完整回答
反对 回复 2019-03-01
  • 3 回答
  • 0 关注
  • 723 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号