Search code examples
javacastingcorba

Duplicate casting


My colleague asks me a question which I can't find the final answer myself, the question is about object casting.

Say I have a class A, and a Factory class, In the factory class, I want to create the A instance:

Public class Factory {

    public A createA1() {
       Object instance = get_A_Object();
       //Single casting
       return (A) instance;
    }

     public A createA2() {
       Object instance = get_A_Object();
       // Duplicate casting or more
       return (A) (A) instance;
    }
}

My question is:

What's the different between single casting in method createA1() vs duplicate casting in method createA2()? Do they always get the same result?

EDIT:

To clarify, my colleague asks me about this line of code:

org.omg.CORBA_2_5.ORB orb = ((org.omg.CORBA_2_5.ORB)org.omg.CORBA.ORB.init((String[])localObject2, localProperties)); 
return (org.omg.CORBA_2_5.ORB)(org.omg.CORBA_2_5.ORB)(org.omg.CORBA_2_5.ORB)(org.omg.CO‌​RBA_2_5.ORB)(orb);

Solution

  • That duplicate is completely redundant. You only have to cast once.

    Here's an exercise. If you load this in your IDE, and remove the casts one-by-one, at what point does it start complaining about your types ?

    In fact, in your amended question, you don't have to cast at all!

    org.omg.CORBA_2_5.ORB orb = ((org.omg.CORBA_2_5.ORB)org.omg.CORBA.ORB.init((String[])localObject2, localProperties));
    

    You've declared orb's type in the assignment.