问题
我用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的属性 。。当然必须要强转语法是这么规定的。