While you are creating any new class you will continually be assessing what properties and methods should be included and, just as importantly, which should be left out.
The decision will always depend on the particular class you are creating, what its purpose is, where it fits into the order of things. If you find yourself in doubt as to whether a class should include a particular member, a good rule of thumb is to leave it out. If it will cause more confusion than clarity, leave it out. If it will be of no use in a majority of scenarios, leave it out. The danger is that if you include too much specialised functionality in a general base class, you restrict its usefulness.
To take the Chess Club scenario that I’ve been using in this series of articles, for example, it makes perfect sense to have the Forename, Surname, Date of Birth and Gender properties in a class named “Person”. A value can be assigned to all person instances for each of those four items of information.
But what if we wanted to create a property that stored the Date that a Person instance joined the Chess Club? All Chess Club members are persons, but all persons are not Chess Club members. It wouldn’t make sense to have such a property in the very generalised Person class. What would make far more sense and would give the greatest flexibility would be to have a Person class that contains those four core properties and have a separate class that contains those four properties, plus the “Date Joined Chess Club” one.
And there lies the solution. Inherited classes. Create a brand new class that inherits all the previously created members (Properties, Fields, Methods, Events) from the Person class and add any further functionality that your more specialised class needs. We briefly saw this happening in an earlier section when we learned that our Person class inherits the functionality of the System.Object class.
You may remember that I described this as a Parent-Child relationship. Let's have a look at how this works and create a child class of our own for the Chess Club project.
Creating Derived Classes
As I explained earlier in the series, in order to show inheritance in action, our overall Chess Club structure includes several classes: a ClubMember class, a Sponsor class and a ClubOfficial class. The hierarchy of these classes is shown below.
As you can see, ClubMember and Sponsor both have Person as a parent class. In real world terms, this makes perfect sense as all instances of ClubMembers and Sponsors will be Persons, with names, dates of birth and gender.
In our Chess Club situation, ClubOfficials must be members of the club. Therefore it is logical that they inherit all the functionality of the ClubMember class, which in turn, as we have just seen, will inherit from the Person class.
Let’s begin by creating the ClubMember class.