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
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;
}