• 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 doubt

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the below problem if i comment out the line at (3) there is no exception thrown but if i uncomment it then it gives a exception.
Will casting of a parent object to child object give a error at runtime?
class CastingExA {}
class CastingExB extends CastingExA {}
public class CastingEx {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CastingExA[] arrA;
CastingExB[] arrB;
arrA = new CastingExA[10];
arrB = new CastingExB[20];
arrA = arrB; // (1)
arrB = (CastingExB[]) arrA; // (2)
arrA = new CastingExA[10];
arrB = (CastingExB[]) arrA; // (3)


}

}
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, if the runtime type of an object is a superclass, then you cannot cast it to a subtype.
reply
    Bookmark Topic Watch Topic
  • New Topic