I can understand what upcasting is but downcasting is a little confusing. My question is why should we downcast? Can you help me with a real world example ? Is downcasting that important?
Downcasting is a necessary evil, for example when dealing with legacy APIs that return non-generic collections. Another classic example is an equals method:
public class Phleem{
public Phleem(final String phloom){
if(phloom == null){
throw new NullPointerException();
}
this.phloom = phloom;
}
private final String phloom;
public String getPhloom(){
return phloom;
}
@Override
public boolean equals(final Object obj){
if(obj instanceof Phleem){
// downcast here
final Phleem other = (Phleem) obj;
return other.phloom.equals(phloom);
}
return false;
}
// ...
}
I can't think of an example where Upcasting is necessary though. OK, it's good practice to return the least specific possible Object from a method, but that can be done entirely without casting:
public Collection<String> doStuff(){
// no casting needed
return new LinkedHashSet<String>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With