Java ClassCastException: Understanding and Fixing Runtime Errors
This code will result in a ClassCastException at runtime.
On line 3, a new Dog object is created and assigned to an Animal reference variable 'a'. Since Dog extends Animal, this is perfectly valid.
However, on line 4, the code attempts to cast 'a' to a Cat object and call the 'catchMouse()' method. Since 'a' is actually a Dog object, and Dog does not have a 'catchMouse()' method, a ClassCastException will occur at runtime.
To fix this error, either create a new Cat object and assign it to 'a', or remove the cast and call a method that is present in both Dog and Cat (such as 'eat()').
原文地址: https://www.cveoy.top/t/topic/ohJG 著作权归作者所有。请勿转载和采集!