• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Another cast prolbem form book

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In complete java 2 certification study guide, chapter 4, figure 4.10.
Newtype is an interface, Oldtype is a non-final class.
Newtype nt; Oldtype ot;
nt = (Newtype)ot; // runtime exception
It said from the book -- always ok. But I try it, but it will throw a ClassCastException. (I try it in JVM1.4)There is no relation between Newtype and Oldtype, I think. Oldtype must implemtns the interface(Newtype) and no matter Oldtype is final or non-final class.
Or this situation will exist in JVM 1.2 or older verison?
Thanks
 
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Kelvin
Yes, it will compile but throw an exception at runtime (book says the same) - what's the problem, then?
By the way, from JLS 5.5


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.
If T is an array type, then S must be the class Object, or a compile-time error occurs.



Regards,
Jamal Hasanov
www.j-think.com
 
"Don't believe every tiny ad you see on the internet. But this one is rock solid." - George Washington
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic