Hello,
I don't understand why we don't get the same result if we change the order of testing the instances.
Can you help me ?
If I start by testing the cat instance then tiger then lion: all 3 return the cat value.
if(o instanceof Tiger) {
return "Tigre";
}
if(o instanceof Lion) {
return "Lion";
}
if(o instanceof Cat) {
return "Chat";
}
order of testing instances
Discussion en cours
Commentaires (1)
- Populaires
- Nouveau
- Anciennes
Tu dois être connecté(e) pour laisser un commentaire
Thomas
27 mars, 00:32utile
Your inheritance hierarchy is eg. Animal -> Cat -> Lion
means a Lion is a Cat is an Animal
If you now have a Lion object and test if it is an Animal than this will be true. If you test for Cat or Lion then these both test will evaluate to true as well. The task however asks you to just output one result and that should be as specific as possible.
That's why you should work with if - else if
Here of course you start with the more specific classes like Lion and Tiger. If it is none of these classes you check for Cat and last but not least the Animal class.
Another possibility would be smth like:
If the object is a Cat or a descendant of Cat or a Bull or a Cow, then return a String representation of the class name. Otherwise return Animal 0