Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Casting  RSS feed

 
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?...
 
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!