Type safety warning - Part II

Q

Qu0ll

Further to the recent discussion on this topic, I have the following
situation that generates a warning and I don't completely understand why.

I have classes A and B and another class:

public class C<T extends B> extends A {
....
}

Now, when I try to do this:

C<D> c = (C<D>)a;

where D extends B and "a" is an instance of A, I get this warning:

Type safety: Unchecked cast from A to C<D>

Why? Is there a way to code around this without suppressing warnings? The
code works fine.

--
And loving it,

-Qu0ll (Rare, not extinct)
_________________________________________________
(e-mail address removed)
[Replace the "SixFour" with numbers to email me]
 
J

Joshua Cranmer

Why? Is there a way to code around this without suppressing warnings?
The code works fine.

The error message is just telling you that it can't certify that the
object is actually a C<D> as opposed to a C<String> or something else.
So yes, you do have to suppress the warnings here.
 
L

Lew

Joshua said:
The error message is just telling you that it can't certify that the
object is actually a C<D> as opposed to a C<String> or something else.
So yes, you do have to suppress the warnings here.

Caveats:

The warning is letting you know that you could have a runtime
ClassCastException ("CCE"). Generics are erased at runtime, and
casting is a runtime deal. If you suppress the warning, you still
might have a CCE.

When you suppress warnings, you must ensure that your code has
prevented the possibility of a CCE at the point of suppression, and
comment that proof with the suppression. This accords with Joshua
Bloch's recommendation in the chapter on generics from /Effective
Java/, freely downloadable from
<http://java.sun.com/docs/books/effective/>
..

You really must read that document if you want to understand Java
generics. It's been recommended multiple times in this forum. There
are also a few very good articles on this matter by Brian Goetz at
IMB's DeveloperWorks site. These documents will repay the study many
times over.
 
D

Daniel Pitts

Qu0ll said:
Further to the recent discussion on this topic, I have the following
situation that generates a warning and I don't completely understand why.

I have classes A and B and another class:

public class C<T extends B> extends A {
....
}

Now, when I try to do this:

C<D> c = (C<D>)a;

where D extends B and "a" is an instance of A, I get this warning:
The runtime environment can't tell whether 'a' is an instance of C<D> or
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,742
Latest member
AshliMayer

Latest Threads

Top