Sunday, 24 April 2016

What is the best way of downcasting objects ?


Child class object can be assigned directly to Parent class reference variable.
When we assign parent object to child class reference, there may following use cases :

UC 1. Direct assignment - Compilation error
// Invalid way
void method(Parent parent) { 
    Child child = parent; // Compile time error
}

UC 2. Downcasting without instanceof check - May be OK or ClassCastException
// Risky way of downcasting
void method(Parent parent) { 
    Child child = (Child) parent; // OK or ClassCastException
}

UC 3. Downcasting with instanceof check - prevents ClassCastException
// Best way of downcasting
void method(Parent parent) { 
     if(parent instanceof Child){ 
          Child child = (Child) parent; // Downcast, if possible
     }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.