0

Class children have different features(its own unique functions), how to use it from Parent class?

Class children have different features(its own unique functions), I want to know how to use it from Parent class? I have parent Class Animal. Two children Class, Dog and Cat. Dog has a function grab(). Cat has a function kick(). If I have to use Class Animal to manage all objects I have, then I have to add both functions grab() and kick() to Class Animal? Then do I have to check the class of the object each time, before I execute grab()? Because if it is a cat, grab() does nothing. Follow up question, how should I check the class? Use instanceof ,getClass(), override equal(obj), switch? Also, another question, what to do if I checked and found that the object is a cat? My friend suggests that uses Exception to skip. But my teacher doesn't recommend this method. I know it is a lot to ask. But I just want to know if I am on the right track. If I should use Interface or abstract class, please let me know.

6th Nov 2022, 1:42 PM
siviaseason
siviaseason - avatar
2 Answers
+ 3
(Abstract) superclasses contain the commonalities of it subclasses. If Dog and Cat distinguish through the methods grab and kick, then neither is in the superclass. You need to reconsider your design...
6th Nov 2022, 3:05 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
You can create a methode in parent class and override it in children to have a different behavior depending on the instantiated type. https://code.sololearn.com/cOwny2lnoTzI/?ref=app
6th Nov 2022, 4:02 PM
Roland
Roland - avatar