• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting  RSS feed

 
Geetha Arthanari
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Animal
{
public String noise()
{
return "animal";
}
}

class Dog extends Animal
{
public String noise()
{
return "dog";
}
}

class Cat extends Animal
{
public String noise()
{
return "cat";
}
}

class Demo
{
public static void main(String args[])
{
Animal a1 = new Dog();
Cat ca = (Cat)a1;
System.out.println(ca.noise());
}
}

Output is:
Exception is thrown at run time
Can anybody explain this please?...
 
Prashant Saraf
Ranch Hand
Posts: 57
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it is like you are converting a dog to Cat. which is practically not possible that why when you run this program at run time your animal has reference to Dog then it get casted to Cat which is not possible and it will give you Typecast exception.
If i miss something let me know.
Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!