Win a copy of TDD for a Shopping Website LiveProject this week in the Testing 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Casting

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
What's brown and sticky? ... a stick. Or a tiny ad.
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic