Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why havinng class cast exception in this code  RSS feed

 
bikasit babu
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • 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?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!