Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error in Java object conversion

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.

like image 818
kikkpunk Avatar asked Dec 05 '25 10:12

kikkpunk


1 Answers

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

Token abc = (Token) n.getInfo();
like image 121
Elliott Frisch Avatar answered Dec 06 '25 23:12

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!