Search code examples
javaobjectcastingsubclasssuperclass

Java object casting behaving strangely


Sorry if this has come up before, but I didn't see another thread about this. But if there is one, please give me the link.

Here I have a simple program. When it runs, it prints out " 6 4 "

public static void main(String[] args) {
    Foo foo = new Foo();
    foo.t = 6;
    foo.f = 4;

    Bar b = new Foo();

    ArrayList<Bar> list = new ArrayList<Bar>();
    list.add((Bar) foo);

    Foo foo2 = (Foo) list.get(0);

    System.out.println(foo2.t + " " + foo2.f);
}

static class Bar {
    int t;
}

static class Foo extends Bar {
    int f;
}

This seems strange, because I would think that when I added the Foo it to the list, it would remove the f field, as the list holds Bars, which don't have an f.

But it seems that the f is sticking around after being casted to a Bar. Could someone explain why this is?


Solution

  • Even if you cast and uncast it n number of times actual object will remain same.
    Casting never add / removes / changes object attributes.

    Bar b = new Foo();
    

    Here reference is of type Bar and actual object is of type Foo. As Foo extends Bar which means it have the attribute f and t (Inherited from Bar) as well.

    list.add((Bar) foo);  
    

    Here you are casting it to Bar (Upasting) but actual object is not changed.

    (Foo) list.get(0);
    

    Here you are casting it back to Foo still object is of type Foo with original values for t and f.