Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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: 13075
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.
 
Lookout! Runaway whale! Hide behind this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic