Upcasting and Downcasting in java

后端 未结 8 1694
孤城傲影
孤城傲影 2021-01-13 21:26

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 th

8条回答
  •  感动是毒
    2021-01-13 21:56

    What You need to remember is that downcasting is allowed when there is a possibility that it suceeds at run time.

    This will work:

    Object o = doStaff();
    String s = (String) o; 
    

    This will fail:

    Object o = new Object();
    String s = (String) s;
    

    Q1: Why we should use downcast ?

    It is generally up to developer, to used the downcast. Sometimes methods return Objects or use as parameter like equal method and then using subcast we can back to specific type.

    Q2: Is downcast important ?

    As everything in coding, but better word would be useful, IMHO it is.

提交回复
热议问题