• 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

why havinng class cast exception in this code

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
package com.bika;
class A
{

}
class B extends A
{

}
class C extends B
{

}
class D extends C
{
}
class E extends D
{

}
public class Manager {
public static void main(String[] args) {
Object o1 = new C();
A a1 = (D)o1;
System.out.println("end");

}
}
in this code at A a1 = (D) o1; gives an exception
but why A a1 = (A) or (B) or (C) o1; wont give any exception
can anybody please explain?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have a look at Ernest's answer in a topic from a few days ago, that will make it clear.

The object you're casting is a C, not a D. Casting will not automatically convert it to a D.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Using real life examples might make it easier:


in this code at Animal a1 = (Hound) o1; gives an exception, because a Canine is not a Hound.
but Animal a1 = (Animal) or (Mammal) or (Canine) o1; won't give an exception. We created a Canine, which IS-AN Animal and IS-A Mammal and IS-A Canine.

Remember - whatever you create, that is what you really have. Casting doesn't change the object type, it just lets you use a different reference type - but the reference type must be valid.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic