
I am helping a friend from first year to prepare his exam on Java.
The teacher asked them to create a method that can cast a Musicians to a Poets.
No one knew how to do it. After thinking a good while, I came to the conclusion that it is impossible to do that(ClassCastException), because the fact that Musician and Poet Share an Interface is not enough to cast them to the other.
I think that would be possible only, if they were in the same inheritance chain.
Now I have three questions:
- Am I right?
- If I am right, what is what the professor wanted from them to do? I really doubt that he would ask for such a thing.
- If I am wrong, could you write code that can cast a Musician into a Poet?
ClassCastException.You could try:
But of course, that code won’t actually work at runtime.