Compilation error in converting Java objects
I have a problem and I am wondering if anyone knows why:
if(n.getInfo() instanceof Token){
//Token abc = n.getInfo();
System.out.print("ouch!");
}
when it starts, it outputs ouch!
.
However, when I uncomment the line
Token abc = n.getInfo();
it gives compilation error:
error: incompatible types: Object cannot be converted to Token
Token abc = n.getInfo();
I don't understand since it is an instance Token
, so how cannot it be converted to Token
?
Thank.
+3
kikkpunk
source
to share
2 answers
You have checked that it is an instance, you need to add a listing
Token abc = (Token) n.getInfo();
+6
Elliott frisch
source
to share
n.getInfo()
can be declared for refund, for example Object
Clearly, if that were the case, it would be the same as saying:
Object blah = n.getInfo();
Token abc = blah;
And it won't work. To fix this, you will need:
Token abc = (Token)blah;
+2
Donald_W
source
to share