• 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

Casting

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program?
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
public static void main(String args[]) {
A x = new A();
B y = new B();
C z = new C();
// insert statement here
}
}
A. x=y;
B. z=x;
C. y = (B)x;
D. z = (C)y;
E. y = (A)y;
The answer given was C. x is handle for A and it was assigned to B handle by casting to B. Was it legal? Somebody please explain.
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Choice A Will compile and run fine. Choices B, D, E won't even compile. C will compile but will throw a ClassCastException.
The compiler allows the cast, since x is a superclass reference but at runtime can point to a subclass object.
HTH
------------------
Velmurugan Periasamy
Sun Certified Java Programmer
----------------------
Study notes for Sun Java Certification
http://www.geocities.com/velmurugan_p/
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic