Skip to content
Advertisement

Why is casting in equals necessary?

I’m doing the Mooc course and it’s teaching us how to compare objects from made up classes like “Person” and see if they are equal to each other. They give us the following code:

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 int getDay() {
    return this.day;
}

public int getMonth() {
    return this.month;
}

public int getYear() {
    return this.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 an 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;
}

}

For the equals method, I get that they compare using == first to check if it’s the same location. Next they see if the compared object is even the same type of object as what you’re comparing it with – if not return false. After that, they convert the compared object into the type of object you’re comparing with then compare the values within. My question is, what’s the point of converting the compared object when you’re already going to return false when they will be different types of objects? Doesn’t

`SimpleDate comparedSimpleDate = (SimpleDate) compared;`

seem to be unnecessary?

Advertisement

Answer

The line is necessary. Otherwise you can not access its data and methods.


Java does not allow you to do compared.getYear() or compared.year because all you know about compared is that it is an Object. So it might be a Cat which does not have a getYear() method, the compiler can not know.

Hence, you have to cast, which means “Hey compiler, trust me, I know that this is actually a SimpleDate, so please allow me to treat it as one”. Which, by the way, will crash at runtime if it actually is not a SimpleDate.


Sure, you checked that it actually is a SimpleDate before, but the compiler is not smart enough to connect the dots. All it knows is that compared is of type Object.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement