-1

My compiler is not showing up any error whereas it does give a run time error can somebody can me whats wrong with the typecasting i did?
Code shows error

Exception in thread "main" java.lang.ClassCastException: class practice.Animal cannot be cast to class practice.Dog (practice.Animal and practice.Dog are in unnamed module of loader 'app'`)

enter image description here

enter image description here

  • 5
    Please post code as properly formatted text, not as images. – Sweeper Jul 08 '20 at 03:17
  • 2
    Does this answer your question? [Downcasting in Java](https://stackoverflow.com/questions/380813/downcasting-in-java) –  Jul 08 '20 at 03:47

1 Answers1

0

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. And because it is a runtime exception, it can't comeup in compile time but in runtime.

Once you create an object, you can't change its type. That's why you can't cast an Animal to a Dog.

However, if you create an object of a sub-class, you can keep a reference to it in a variable of the super-class type, and later you can cast it to the sub-class type.

This will work :

Animal a = new Dog ();
Dog d = (Dog) a;

This is how you deal with ClassCastException :

  1. Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.

  2. You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.

Sanket Singh
  • 1,246
  • 1
  • 9
  • 26