Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #38479
| From | Eric Sosman <esosman@comcast-dot-net.invalid> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: Casting without Generics |
| Date | 2018-07-09 17:59 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <pi0lsf$lkk$1@dont-email.me> (permalink) |
| References | <casting-20180709205142@ram.dialup.fu-berlin.de> |
On 7/9/2018 3:54 PM, Stefan Ram wrote:
> The following programm yields no compile-time error
> using the JDK 10:
>
> Main.java
>
> public final class Main
> { public static void main( final java.lang.String[] args )
> { final java.lang.CharSequence cs = "abc";
> java.lang.System.out.println( ( java.io.PrintStream )cs ); }}
>
> transcript
>
> Exception in thread "main" java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.io.PrintStream
> at Main.main(Main.java:4)
>
> Why?
It surprised me, too -- at first. But consider:
class Perverse extends PrintStream implements CharSequence {...}
... is certainly not forbidden, and if you were to write such a thing
it would then be possible to have a CharSequence instance that would
survive the cast-check with no trouble at all. The mere fact that some
reference is to a CharSequence does not imply that it cannot also be
to a PrintStream.
> I used to believe that the compiler would complain that
> »java.io.PrintStream« is neither a super- nor a subtype
> of »java.lang.CharSequence«.
>
> Did I miss something?
The rules are spelled out in JLS 5.1.6, with special reference
to 5.1.6.1-3. Roughly speaking, the compiler need not object to a
conversion that is *possibly* valid if there exists a foolproof way
to check the validity at run-time. (If there's no foolproof run-time
check the compiler must object unless the conversion is *assuredly*
valid.)
--
esosman@comcast-dot-net.invalid
Nine hundred twenty-six days to go.
Back to comp.lang.java.programmer | Previous | Next | Find similar | Unroll thread
Re: Casting without Generics Eric Sosman <esosman@comcast-dot-net.invalid> - 2018-07-09 17:59 -0400
csiph-web