Upcasting and Downcasting in java

后端 未结 8 1621
孤城傲影
孤城傲影 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:48

    Downcasting is needed when you receive an object that you know has some more specific (down the class hierarchy) type and you want to cast it to that type.

    Example: you receive Object from some service and you know that it is actually String and you downcast it to String. Before downcasting you should always check the type otherwise you risk the ClassCastException:

    Object receivedObject = receiveFromSomewhere();
    if(receivedObject instanceof String){
        receivedString = (String) receivedObject;
    }
    

提交回复
热议问题