Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubts about object Casting

Tags:

java

enter image description here

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:

  1. Am I right?
  2. 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.
  3. If I am wrong, could you write code that can cast a Musician into a Poet?
like image 345
javing Avatar asked May 18 '11 22:05

javing


1 Answers

  1. You are right
  2. Trick question?
  3. No, at least, not without a ClassCastException.

You could try:

 Musician musician = new Musician();
 Artist artist = musician;
 Poet poet = (Poet)artist;

But of course, that code won't actually work at runtime.

like image 82
Kirk Woll Avatar answered Oct 04 '22 02:10

Kirk Woll