First time posting here in a while, so I am very sorry if I made any mistakes.
I am learning java from MOOC fi. I am currently in week 5 and it mentions here that to compare two objects, you have to do the following:
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the type of the compared object is not SimpleDate, the objects are not equal
if (!(compared instanceof SimpleDate)) {
return false;
}
// convert the Object type compared object
// into a SimpleDate type object called comparedSimpleDate
SimpleDate comparedSimpleDate = (SimpleDate) compared;
// if the values of the object variables are the same, the objects are equal
if (this.day == comparedSimpleDate.day &&
this.month == comparedSimpleDate.month &&
this.year == comparedSimpleDate.year) {
return true;
}
// otherwise the objects are not equal
return false;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
So I am confused, what does:
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
the above code actually do? What does located in same position mean?
Isn't it better to just check if an object is of a particular class type and then compare their instance variables to see if they are equal?