valleyvova.blogg.se

Java downcast by design
Java downcast by design













As shown above, you normally risk a ClassCastException by doing this however, you can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastExceptions: Animal animal = getAnimal() // Maybe a Dog? Maybe a Cat? Maybe an Animal?

java downcast by design

To call a subclass's method you have to do a downcast. To call a superclass's method you can do thod() or by performing the upcast. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException. However, if you were to do this: Animal animal = new Animal() In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal. The compiler will allow the conversion, but will still insert a runtime sanity check to make sure that the conversion makes sense. In general, you can upcast whenever there is an is-a relationship between two classes.ĭowncasting would be something like this: Animal animal = new Dog() īasically what you're doing is telling the compiler that you know what the runtime type of the object really is. In your case, a cast from a Dog to an Animal is an upcast, because a Dog is-a Animal.

java downcast by design java downcast by design

Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException. Upcasting is casting to a supertype, while downcasting is casting to a subtype.















Java downcast by design