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

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
//------------------------------------
class Parent{}
class Child extends Parent{}

class A {
public static void main(String[] s)
{
Parent p = new Parent();
Child c = (Child) p; // compiles fine
//but gives a cast Exception at runtime
}
}
Can you explain why it is giving a cast exception at runtime please?
Thank you
 
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because p is not in fact a Child but a Parent. At compile-time the compiler "trusts" you when you cast down, but at run-time the object that you cast better actually be what you said it was or you'll get a runtime exception.
 
zaher
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you . It's clear now
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
At compile-time the compiler "trusts" you when you cast down, but at run-time it finds that you are Casting with the parent object,since both are incompatible or you'll get a runtime exception.
Child c = (Child) p;
By above line of code, it is nothing but saying parent = child,which is wrong.Parent can have all the properties of the child,but child cannot have all the properties of the parent.
Cheers,
Ravi
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
zaher,
Welcome to Javaranch, a friendly place for Java greenhorns
We ain't got many rules 'round these parts, but we do got one. Please change your displayed name to comply with the JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic