What is a practical use of casting on an object in Java? (Lesson Downcasting)
Here is the text from the lesson Downcasting from Java Intermediate. Upcasting You can cast an instance of a subclass to its superclass. Consider the following example, assuming that Cat is a subclass of Animal. Animal a = new Cat(); Java automatically upcasted the Cat type variable to the Animal type. Downcasting Casting an object of a superclass to its subclass is called downcasting. Animal a = new Cat(); ((Cat)a).makeSound(); This will try to cast the variable a to the Cat type and call its makeSound() method. I understand the upcasting part, since Cat is a subclass of Animal. But what is the practical use of downcasting an object? And In my code linked, animal a, b and c works as expected. However, if I initiated a new Animal d and downcasting it to a cat it gives error. I thought it forces (casting) class animal d to a class cat temporally, but the code shows me wrong. https://sololearn.com/compiler-playground/cytZMvF8biXf/?ref=app