stephencurry30
stephencurry30

Reputation: 127

Trouble understanding inheritance and implementing it in classes

I am having trouble understanding inheritance and implementing it in classes. I am trying to create a program with the Reptile class as the base.

What's the best way to do this with the following data?

There will also be a menu class using what I think should be a switch case to select the desired reptile and display the information.

Thanks in advance for any help.

enter image description here

Upvotes: 1

Views: 75

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

Ok, so I understand that this is some kind of homework exercise, since in the real world you will not use inheritance for this at all.

using the the image you posted, let me try to explain inheritance in the simplest terms I can.

You can think of a base class for all reptiles - Let's call it Reptile.
This class contains all the different aspects shared by all reptiles - things like preferred food, feeding time, food to weight ratio etc'.
All of these aspects can be coded as properties of the Reptile class.

Please note that in the real world, the Species and ReptileType would also be properties of the Reptile class, making the use if inheritance completely redundant in this case - But then again, we are not talking about real world applications yet - so:

A Snake is a specific type of Reptile. A Lizard is another specific type of Reptile - so let's create classes for those two types. So far, we have the Reptile, Snake and Lizard classes, where the last two inherits the first.
Moving on, a Cobra is a specific type of Snake, so is a Rattlesnake. So let's create classes for them inheriting from Snake. Much the same, a BeardedLizard is a specific type of Lizard, and so is a Chameleon - so here are another two classes to create.

So basically, I think your teacher is expecting to see the following:

class Reptile {/* implementation here */}
    class Snake : Reptile {/* implementation here */}
        class Cobra : Snake {/* implementation here */}
        class Rattlesnake: Snake {/* implementation here */}
    class Lizard: Reptile {/* implementation here */}
        class BeardedLizard : Lizard {/* implementation here */}
        class Chameleon : Lizard {/* implementation here */}

Now, the reason inheritance does not make sense in this situation, is that a Snake does not add any new capabilities to a Reptile, nor does a Chameleon to a Lizard. For inheritance to make sense, you will need to add new capabilities in the deriving types, that is specific to that class (and it's inheritors) and is not shared with the base class or any other inheritance chain of that class.

For instance, all snakes crawl, while all lizards walk. If you where to add a Crawl() method to the Snake class and a Walk() method to the Lizard class - Than it would make sense for a Snake and a Lizard class inheriting the Reptile class.

Upvotes: 1

Related Questions