I tried to perform a comparison between two objects of the same class. Actually, I wanted to compare the content of the both the objects. Here, the objects are of class Student. In class Student I have overridden the equals()
method as shown below.
By doing so, will my intention be accomplished (compare the names and birthdays of both students)? If not what is happening here?
The problem is that I don't get the answer I expect. The output is false
even though it must be true
.
public class Main {
public static void main(String[] args) {
Student a = new Student("John", "Johnny");
Student b = new Student("John", "Johnny");
a.setBirthDate(10, 10, 10);
b.setBirthDate(10, 10, 10);
boolean ans = Student.equals(a, b);
System.out.println(ans);
}
}
public class Date {
public int day;
public int month;
public int year;
public Date(int d, int m, int y) {
this.day = d;
this.month = m;
this.year = y;
}
}
public class Student{
private String firstName;
private String lastName;
private Date birthDate;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setBirthDate(int day, int month, int year) {
Date b_day = new Date(day, month, year);
birthDate = b_day;
}
}
@Override
public boolean equals(Object student) {
System.out.println(this.firstName);
System.out.println(this.lastName);
System.out.println(this.birthDate);
System.out.println(((Student)student).firstName);
System.out.println(((Student)student).lastName);
System.out.println(((Student)student).birthDate);
return super.equals(student);
}
I have overridden the equals method as follows. But still I face the same issue. I suspect that there's something wrong with the Date
class. But the problem is that I'm not quite sure of it. Also, I don't understand how to remedy the problem. Can someone please tell me what's wrong here.
Thanks in advance.