Search code examples
javacastingscjpocpjp

Solving upcasting/downcasting problems


Does anyone have any workable strategy for solving casting/upcasting questions? I understand when upcasting and downcasting is allowed but when the questions tend to have multiple objects involved i tend to get confused pretty quickly. For example, what is the best approach to finding the answer to a question like this:

Question: What would be the result of compiling the following program:

interface Inter{}
class Base implements Inter{}
class Derived extends Base{}

class ZiggyTest2{

    public static void main(String[] args){

        Base b = new Base();
        Derived d = new Derived();
        Inter i = (Base)b;
        i = (Base)d;
        Derived bd = (Derived)b;
        b = (Base)i;        
    }   
}

I am not really interested in the answer but more the approach to solve the question. Is there any approach/strategy i can use to solve an upcasting/downcasting question like above? For example can the references/objects be drawn on paper so that i can get a visual representation and can that help?

Thanks


Solution

  • If the objects being operated are in the same hierarchy, casting will compile for sure, but it might fail at runtime.

    E.g.:

    class Animal { }
    class Dog extends Animal { }
    class Bulldog extends Dog { }
    

    If you write:

    Animal animal = new Animal();
    Dog d = (Dog) animal;
    

    Above code will compile, but it will fail at runtime. Because all the compiler can do is check if the two types are in the same inheritance tree. Compiler allows things which might work at runtime. But if the compiler knows for sure that something will never ever work, it will throw error at runtime itself. E.g.

    Animal animal = new Animal();
    Dog d = (Dog) animal;
    String s = (String) animal;
    

    This will surely fail as the compiler knows that String and Dog are not in the same hierarchy.

    The same rules apply to interfaces as well.

    Hope it helps.