I’ve been working on OOP methods lately, and here is something I’ve always been wondering.
Let say we have the following situation. We have a collection of pets [dog, cat, mouse].
Each pet has the same behaviour: running, eating, sleeping. Furthermore, they all have a different visual representation.
Instead of making 3 seperated classes and recreate those 3 functions like this:
- dog
- eat function
- run function
- sleep function
[same goes for cat and mouse]
Is there a better way to simply “share” a collection of functions between these different classes, and somehow differ the behaviour of these function depening on the chosen class (the walking speed of a dog might be quicker than a cat, a cat might sleep more than a mouse etc).
I’ve looked at interfaces, but as far as I understood you can’t actually code the functions, the interface just acts of a list of requirements that a class should have. Could be very wrong tho. Help is much appreciated 🙂
Sounds like you just need inheritance?
I use this sort of thing all over my games.
To differ depending on the subclass:
If it’s a big change, then obviously you should override the method in the subclass.
If it’s a small change, you might choose to give the behaviour to the parent class and use member variables to alter it slightly:
Personally I never found interfaces terribly useful in AS3 — every time I tried using them I ended up refactoring them later into classes instead, when I realised I wanted to share functionality between the implementations.