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:

JavaScript

}

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

JavaScript

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