0

Here is my sample code:

public class Bar extends Foo {
}

@SuppressWarnings("unchecked")
public class Foo {

    public static void main(String[] args) {
        Foo foo = new Bar();
        Class<Foo> x = (Class<Foo>) foo.getClass();
        System.out.println(x);
    }
}

Well I am expecting this programs output to be: Foo.class since I am casting to Class however I see in output:

class Bar

Why?

If I remove the casting part from the code, program will not even compile:

java: incompatible types
required: java.lang.Class<Foo>
found:    java.lang.Class<capture#1 of ? extends Foo>

Why is the compiler forcing me to cast?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • @RealSkeptic How are these questions same? – Koray Tugay Nov 01 '15 at 14:06
  • Well, an `A` is not an `A` even when there is some connection between `X` and `Y,` that's why you can't assign from a `Class extends X>` to a `Class`. That's the gist of that question, and the gist of the problem in yours. – RealSkeptic Nov 01 '15 at 14:35

1 Answers1

1

Why?

Because the class of the object is Bar, not Foo (you created the object with new Bar()), and you've explicitly asked the object what class it is. You have a Foo reference to the object, but that doesn't change what the object actually is.

If I remove the casting part from the code, program will not even compile:

That's unrelated to the Foo/Bar thing. You've given x a specific type (Class<Foo>), but Object#getClass is typed Class<?>.


From your comment:

Yes well, I asked the object itself, but then I cased it to a Class<Foo> and stored the data in 'x'. This is confusing me..

Casting has no effect on the object at all, casting is purely about changing the type of the reference you have to the object. It's the same object, unchanged, all you've done is change the type of your reference to it. This can change what aspects of the object you have access to, and can (of course) fail if you try to cast to something that the object isn't.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Yes well, I asked the object itself, but then I cased it to a Class and stored the data in 'x'. This is confusing me.. – Koray Tugay Nov 01 '15 at 13:40
  • 1
    Casting doesn't change the type of an object. Casting a mouse, referenced as an Animal, to an Elephant, won't transform the mouse into an elephant. It will fail, because a mouse is not an elephant. Casting an Animal to Elephant is only valid if the animal is, indeed, an Elephant. Your cast doesn't fail because generics are erased: at runtime, Java can't distingish a Class from a Class. But your compiler warned you that this was an unsafe cast: it can't check that the class is indeed a Class. If it could, the cast would have failed. – JB Nizet Nov 01 '15 at 13:42