Ask your own question, for FREE!
Computer Science 6 Online
OpenStudy (anonymous):

Interfaces are confusing me. I have asked classmates and no one knows, can you answer this? Suppose C is a class that implements the interfaces I and J. Which of the following assignments require a cast? C c = . . .; I i = . . .; J j = . . .; a. c = i; b. j = c; c. i = j; Thank you so much!

OpenStudy (anonymous):

In general, a cast can be done implicitly only when it is 'safe', otherwise it has to be specified explicitly. A good way to understand it is by an example. In this case let's use direct inheritance, but it's the same idea when implementing interfaces. Say you have two classes `Zebra` and `Elephant` that inherit from `Mammal`. Obviously you can do: ``` Zebra z = new Zebra(); Elephant e = new Elephant(); ``` But the thing is, because `Zebra` inherits from `Mammal` (since logically every zebra is necessarily a mammal..) then the following logically works `Mammal m_z = new Zebra()`. Likewise we can do `Mammal m_e = new Elephant()`. But notice that the opposite is not logically true. A mammal is not necessarily a zebra (or an elephant). The cast from Mammal to Zebra is not safe, because `Zebra z = m_e` results in trying to treat an Elephant object (treated as Mammal) as a Zebra object, but an elephant is not a zebra.. oops. However that doesn't mean that the cast is always bad. The assignment `Zebra z = m_z` tries to treat an actual Zebra object (treated as Mammal) as a Zebra object. The thing is, as seen above, that the cast is not "safe", but not necessarily wrong. So if we want to perform such a cast we have to do so explicitly `Zebra z = (Zebra)m_z`. If you'd try this with an elephant: `Zebra z = (Zebra)m_e` the program would compile, but it performs bad cast which usually results in a runtime error trying to do so (depends on the language).

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!