• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

ClassCastException Doubts

 
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From web page


1. x = y
2. z =x;
3. y = (B)x;
4. z = (C)y;
5. y = (A)y

In the above I know 3rd will cause runtime exception.
Why y = (A)y is compile time exception. pls explain..
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
y=(A)y;

y on the left has type "B",
(A)y on the right has type "A",
"A" isn't a "B", the assignment fails, so compiler detects type mismatch
 
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. x = y
This is OK as a super class reference can hold the subclass reference(can refer to the object which subclass was refering) without any explicit cast.
So will pass both the compile time and runtime test.
2. z =x;
require explicit cast.Compilation fails.
3. y = (B)x;
x can be casted to y as both A and B are part of same inheritance lineup.Compilation succeds.Runtime fails downcasting not possible.
4. z = (C)y;
y can not be casted to z,not in the same inheritance hierarchy.
5. y = (A)y
Compilation fails sub class(B) can not hold the reference of super class (A) without a explicit cast. To make it work change something like y = (B)((A)y).
 
reply
    Bookmark Topic Watch Topic
  • New Topic