Originally posted by Reshma Pai:
Whats the difference
'Test t = (Test) c;'
from the above code and
'String s = (String) new StringBuffer();'
The following is a quote from
Section 5.5 of the Java Language Specification.
"Some casts can be proven incorrect at compile time; such casts result in a compile-time error."
A cast from StringBuffer to String would fall into the "can be proven incorrect at compile time" category. The compiler knows that a StringBuffer is not a subclass of String so the cast results in a compile time error.
The compiler accepts the following cast
Test t = (Test) c;
Because Test is an interface and because a subclass of Check might implement Test.
The following is another quote from Section 5.5 of the JLS.
The remaining cases involve conversion between reference types. The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
If S is a class type:
If T is a class type, then S and T must be related classes-that is, S and T must be the same class, or S a subclass of T, or T a subclass of S; otherwise a compile-time error occurs.
If T is an interface type:
If S is not a final class (�8.1.1), then the cast is always correct at compile time (because even if S does not implement T, a subclass of S might).If S is a final class (�8.1.1), then S must implement T, or a compile-time error occurs. [ March 29, 2003: Message edited by: Dan Chisholm ]