Got a task to make a program that registers animals and the object is to get familiar with inheritance, polymorphism and so on.
One thing that pussles me is no matter how much I read about it just seems pointless.
I create my main class which is animal with some generic fields that apply to all animals lets say name, age and species.
So far so good all animals has this info but every animal has a unique field aswell so ill create my cat as public class cat : animal and give the cat the field teeth for example.
Now I want to make a new animal which is a cat, im taking data from several listboxes so I would need a constructor that takes those parameters and this is what I dont get, do I have to declare them in every child class aswell?
I know that my animal should have 3 parameters from the animal class plus another from the cat class so the new cat should accept (name, age, species, teeth) but it seems that I have to tell the constructor in the cat class to accept all of these and theres my question, what purpose does the animal class serve? If I still need to write the code in all subclasses why have the base class? Probably me not getting it but the more I read the more confused I become.
Like Sergey said, its not only about constructors. It saves you having to initialize the same fields over and over. For example,
Without inheritance
With Inheritance
Everything common to animals gets moved to the base class. This way, when you want to setup a new animal, you don’t need to type it all out again.
Another advantage is, if you want to tag every animal with a unique ID, you don’t need to include that in each constructor and keep a global variable of the last ID used. You can easily do that in the Animal constructor since it will be invoked everytime the a derived class is instantiated.
Example
Now when you do;
If you want a list of all Animals in your ‘farm’,
without inheritance
With inheritance
This way, if you want to see if you have an animal called
Pluto, you just need to iterate over a single list (animals) rather than multiple lists (Cats, Dogs, Pigs etc.)EDIT in response to your comment
You don’t need to instantiate Animal. You simply create an object of whichever Animal you want to. In fact, since an Animal will never be a generic Animal, you can create
Animalas an abstract class.Edit to your comment
If you store it in a list of Animals, you still have access to all fields. You just have to cast it back to its original type.