简体   繁体   中英

Casting derived to base, and then casting that into another derived. Java

So I have 3 classes.

base

derived1 derived from base

derived2 derived from base

This code says that derived1 cannot be casted to derived2, even though I already casted derived1 to a base object?

base temp = (derived2)((base)derived1);

I'm trying to cast derived1 into a derived2 object. And this was the only solution I could come up, is this valid? And is there any other way to achieve this? Thanks!

You cannot do that. You will certainly end up with nothing more than a ClassCastException .

If your method is a non-final method of base (possibly overridden in subclasses) then you can cast both to a base and call it that way.

You can also make proper use of interfaces to represent common functionality instead.

The only means of dynamic binding that Java offers is via reflection ( tutorial , also java.lang.Class documentation ), eg:

myObject.getClass().getDeclaredMethod("display").invoke(myObject);

Bear in mind that you lose all benefits of compile-time type checking when using reflection (and also the interface is much more cumbersome) -- there is almost always a better way to accomplish the task without it (in your case, I have a hunch that there is most definitely a better way).

In general, the code indicates the design problem. Ensure derived1 and derived2 ' is-a ' base , please.

How does a banana cast to an orange?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM