Domanda

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!

È stato utile?

Soluzione

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), e.g.:

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).

Altri suggerimenti

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

How does a banana cast to an orange?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top