Forums Register Login

Casting

+Pie Number of slices to send: Send
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?...
+Pie Number of slices to send: Send
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!
I child proofed my house but they still get in. Distract them with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 401 times.
Similar Threads
question from Dan's exam - ClassCastException
Could anyone give some example for this statement
Doubt Example
Casting
invalid cast exception
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:47:45.