3

I have a problem and I'm wondering if anyone knows why:

if(n.getInfo() instanceof Token){
   //Token abc = n.getInfo();
  System.out.print("ouch!");
}

when it runs, it prints out ouch!.

However, when I uncomment the line

  Token abc = n.getInfo();

it gives a compile error:

error: incompatible types: Object cannot be converted to Token
        Token abc = n.getInfo();

I don't understand, as it is an instance of Token, so how it cannot be converted to Token?

Thanks.

1
  • 2
    Just a note; when you're using instanceof it probably means you're doing something not very OO style. I'd say it's a telltale sign to have a good look at your code. Commented Dec 21, 2014 at 0:08

2 Answers 2

6

You've tested that it's an instance, you need to add a cast

Token abc = (Token) n.getInfo();
Sign up to request clarification or add additional context in comments.

1 Comment

You might want to mention that the giveaway here is the return type delcared for getInfo()...
2

n.getInfo() could be declared to return, for example, Object

Clearly if this was the case, it would be the same as saying:

Object blah = n.getInfo();
Token abc = blah;

And that wouldn't work. To fix it, you would need:

Token abc = (Token)blah;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.