Question about casting
Hi, I'm reading JLS third edition, chapter 5.5, casting conversions.
The specification, where the compile-time legality rules of cast conversion between a compile-time type S (source) to a compile-time type T (target) are defined, states:
[quote]
...If S in an interface type:
[...etc]
If T is a type that is not final, then:
[...etc]. Otherwise the cast is always legal at compile time (because even if T does not implement S, a subclass of T might).
[/quote]
I've got the following code:
package uk.co.jemos.experiments;
import java.io.Serializable;
import java.util.List;
publicclass GenericMain{
interface MyInterface{}
staticclass MyTypeimplements MyInterface{}
public GenericMain(){
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
publicstaticvoid main(String[] args){
MyType T =new MyType();
Cloneable S = (MyType)T;//Compile time error
}
}
Here I'm trying to convert the variable S (the source, which is an interface type) to the non-final type MyType, but I get a compile time error.
What am I doing wrong?
[2033 byte] By [
mtedonea] at [2007-11-27 1:06:57]

> Casting T to MyType is pointless, because that's what
> it's declared as.
>
> It also doesn't help you because the result of the
> cast is MyType, which does not implement Cloneable.
> You need to cast to Cloneable, not MyType.
I wasn't trying to write some meaningful code here, I would never write such code in real life, but I was just trying to write some code to put in practice what the JLS is saying about casting.
I was trying to achieve something like:
Interface I = (NonFinalType)someReferenceVar;
Does the JLS mean that NonFinalType could be the same Interface I since Interfaces can't be declared final?
> > Casting T to MyType is pointless, because that's
> what
> > it's declared as.
> >
> > It also doesn't help you because the result of the
> > cast is MyType, which does not implement
> Cloneable.
> > You need to cast to Cloneable, not MyType.
>
> I wasn't trying to write some meaningful code here, I
> would never write such code in real life, but I was
> just trying to write some code to put in practice
> what the JLS is saying about casting.
Okay, but you still have to use code that's applicable to what you're asking. Based on what you wrote, there's no way I could guess what you really meant.
jverda at 2007-7-11 23:42:09 >
