Try to do typecast but getting CAP#1 error

java

Solution

The first problem is that you're trying to use an instance of `Class` as a type cast. That's not valid - it has to be a type.

That aside, if you try to do (I've renamed `myObj` to `MyObj` for clarity / proper naming):

ImyObj testObj = new MyObj();
MyObj testObj2 testObj.getClass().cast(testObj);

It won't work.

`testObj.getClass()` is going to return a `Class<? extends ImyObj>` which is "Something that extends ImyObject". It can't be used to cast to a specific subclass; that's what the error is saying.

If you used:

MyObj testObj2 = MyObj.class.cast(testObj);

It would work; you're using the specific class. The same would be true if you had:

MyObj mo = new MyObj();
MyObj testObj2 mo.getClass().cast(testObj); 

In this case `mo.getClass()` returns a `Class<? extends MyObj>` which can be used to cast to a `MyObj` because the target is a `MyObj` rather than some subclass of `MyObj`

And if `testObj` wasn't an instance of `MyObj` it would throw a `java.lang.ClassCastException`

Problem

Playing around with type casting for a project I am about to start I found this error unexpectedly: ``` incompatible types: Class<CAP#1> cannot be converted to myObj where CAP#1 is a fresh type-variable: CAP#1 extends ImyObj from capture of ? extends ImyObj ``` The code that caused this error: ``` ImyObj testObj = new myObj(); System.out.println(testObj.sayHi()); myObj testObj2 = (testObj.getClass()) testObj; System.out.println(testObj2.sayBye()); ``` However this works fine: ``` ImyObj testObj = new myObj(); System.out.println(testObj.sayHi()); myObj testObj2 = (myObj) testObj; System.out.println(testObj2.sayBye()); ``` Shouldn't they both do the same thing or am I missing something? I currently have Java 1.7_51 installed. It has been a while since I touched Java(before 1.7), as I got immersed in Python 2.7. EDIT: Louis Wasserman's answer also raises the same error.

Original source