I am a beginning programmer and came across this in my textbook:
public boolean equals(DataElement otherElement)
{
IntElement temp = (IntElement) otherElement;
return (num == temp.num);
}
IntElement is a subclass of DataElement. num is an int storing a value for a linked list.
What is the purpose of (IntElement) after temp =? What would be wrong with IntElement temp = otherElement? And, in general, what does putting a data type in parentheses like that do?
This is called casting, see here:
Basically, by doing this:
you are telling compiler to ignore the fact you declared
otherElementasDataElementand trust you it is going to be anIntElementand notDataElementor some other subclass ofDataElement.You cannot do just
IntElement temp = otherElement;as this way you would makeotherElement, which was defined asDataElementbecome some other element, in this caseIntElement. This will be a big blow to type-safety, which is the reason types are defined at the first place.This could technically be done using type inference:
however Java does not support that and you have to be explicit.
If it’s possible to get other elements, you may want to use
instanceofto check the type runtime before casting:At some point after you go through this, you might want to take a look at generics, too: