Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upcasting and Downcasting in java

Tags:

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

like image 727
Sumithra Avatar asked Dec 13 '22 18:12

Sumithra


1 Answers

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>();
}
like image 100
Sean Patrick Floyd Avatar answered Dec 28 '22 05:12

Sean Patrick Floyd