Sumithra Sumithra - 14 days ago 5
Java Question

Upcasting and Downcasting in java

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 time example ? Is downcasting that important?

Answer

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>();
}
Comments