Im learning c# and have troubles understanding what use cases inheritance has in comparison to instances?
To put it into a context, i am making a console rpg, and my current understanding is that I should make a superclass/baseclass npc
from which I inherit 3 subclasses mage
, paladin
and thief
, from which i each instance High level mage
, low level mage
.
Does it make sense or is there a problem in my logic? Would this also work the other way around with inheritance/instance swapped?
>Solution :
Comparing instances to inheritance is akin to comparing apples and oranges. They are more or less unrelated. Inheritance is used to define the heirachy of class definitions, whereas instances are when you create an actual instance of one of those classes.
One (but by far not the only) question you need to ask yourself when considering if inheritance is the right choice is do the subclass and superclass share an is a relationship? If the answer is yes, you might want to use inheritance. If the answer is maybe or no then you almost certainly don’t.
To give you some examples.
q: Does a class Mercedes
share an is a relationship with a class Car
.
a: Maybe! It’s much more likely you just simply have a class Car
which has a property which is it’s Make
(and Model
etc).
q: Does a MyWebPage
share an is a relationship with class BaseWebPage
a: Probably, yes. This is a common way that inheritance is used. MyWebPage
overrides some functionality of the base class to control rendering (as one example)
Back to your example. Does class Mage
Share an is a relationship with Npc
…. answer is another "Maybe". For it to make sense to use inheritance your Mage
must override some of the base functionality of Npc
– you might have something like the Car
example above.