public static void doWork(Person person) {
if(person instanceof Person.User){
((Person.User) person).live();
}
else if(person instanceof Person.Loser){
((Person.Loser) person).doNothing();
}
else if(person instanceof Person.Coder){
((Person.Coder) person).writeCode();
}
else if(person instanceof Person.Programmer){
((Person.Programmer) person).enjoy();
}
}
Could anyone can clarify it why do I need to cast person to Person.xxx to call method? It works but Intellij done that for me and I don't know why ;/
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
horst
13 September 2020, 09:08useful
This was - and to some extent still is - puzzling me as well. Broadly speaking, the doWork-method takes some general "Person"-object as an input and the instanceOf-Operator just checks whether the Person-object could possibly be downcasted/converted to the more specific Coder/Loser/etc. It does not automatically convert the Person, it just verifies whether it would be possible to use this Person-object as a Programmer/User/etc. If it returns true, you can now safely cast the fuzzy "I-can-be-anything"-object to a more concrete instance.
Or, as a nice analogy I read somewhere on stackoverflow puts it:
"There's a difference between measuring if some object will fit in a box, and actually putting it in the box. instanceof is the former, and casting is the latter."
+2