Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #38479 > unrolled thread

Re: Casting without Generics

Started byEric Sosman <esosman@comcast-dot-net.invalid>
First post2018-07-09 17:59 -0400
Last post2018-07-09 17:59 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.java.programmer

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Casting without Generics Eric Sosman <esosman@comcast-dot-net.invalid> - 2018-07-09 17:59 -0400

#38479 — Re: Casting without Generics

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2018-07-09 17:59 -0400
SubjectRe: Casting without Generics
Message-ID<pi0lsf$lkk$1@dont-email.me>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web