How can I cast base to a drived class?

Is there a work around that will allow me to cast an object of the base class to an object of the derived class?

something like the following

B extends A

A a = new A();
B b = (B)a

Is there a trick that will achieve this?

Jon Skeet
people
quotationmark

No, absolutely not. What would you expect the values of any fields declared in B but not in A to be? For example, what would you expect this to do:

Object x = new Object();
String text = (String) x;
System.out.println(text);

An Object has no text data... so what would it mean to cast it as a string?

You can only cast a reference to a type which is appropriate for the actual type of the object.

The desire to do this usually indicates a design problem somewhere... or it might mean that you want something like:

public class A {
    public A() { 
        // Whatever
    }

    public A(A a) {
        // Use the existing values in "a" to initialize this object
    }
}

public class B extends A {
    /** Creates a new B from the values in an A, with suitable defaults. */
    public B(A a) {
        super(a);
        // Now initialize any fields in B with appropriate values
    }
}

Then:

A a = new A();
B b = new B(a);

That will create two objects, unlike a cast... but it would at least be valid.

people

See more on this question at Stackoverflow