views:

211

answers:

2

Considering following code

   public class A {

    public static void main(String[] args) {
        new A().main();
    }

    void main() {

        B b = new B();
        Object x = getClass().cast(b);

        test(x);
    }

    void test(Object x) {
        System.err.println(x.getClass());
    }

    class B extends A {
    }
}

I expected as output "class A" but i get "class A$B".

Is there a way to cast down the object x to A.class so when using in a method call the runtime will think x is of A.class ?

+5  A: 

A cast doesn't change the actual type of the object. For example:

String x = "hello";
Object o = (Object) x; // Cast isn't actually required
System.out.println(o.getClass()); // Prints java.lang.String

If you want an object which is actually just an instance of A, you need to create an instance of A instead. For instance, you might have:

public A(B other) {
    // Copy fields from "other" into the new object
}
Jon Skeet
yes, after further thinking i got the same conclusion ! Thanks.
PeterMmm
A: 

No. Casting doesn't change the type of an object, it just changes what type you have a reference to.

For example, this code:

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

Doesn't take b and forcibly make it into an instance of A, and then call the doSomething() method in class A. All the casting does is allow you to reference the object of type B as if it were of type A.

You cannot change the runtime type of an object.

matt b