The Syntax and Terminologies

In this lesson, you will learn how to use inheritance and the terminologies related to it.

The Terminologies

Since we know that a new class is created based on an existing class in inheritance, we use the terminology below for the new class and the existing class:

  • Base Class (Mother Class or Superclass): This class allows the re-use of its non-private members in another class.
  • Derived Class (Child Class or Subclass): This class is the one that inherits from the superclass.

A child class has all non-private characteristics of the mother class.

What Does a Child have?

An object of the child class can use:

  • All members defined in the child class.
  • All non-private members defined in the mother class.

In C#, we can declare some classes non-inheritable using the keyword, sealed, like: public sealed ClassName {...}.

Implementation

In C#, to implement inheritance, we have to use the colon : operator. The generic syntax looks like the following:

SubClass : SuperClass{
//contents of SubClass
}

Let’s jump back to our example of a VendingMachine. In a food vending machine, we have got several types of products e.g. beverages, chocolates, biscuits, etc. Now the noticeable thing here is that we always implement an inheritance relationship between classes when they have some of the attributes in common. For example, in the case of the products, all the products have names, prices, expiry dates, etc. Also, the IS A relationship stands valid in this case as we can say:

  • A beverage is a product.
  • A chocolate is a product.
  • A biscuit is a product.

So, from the above discussion, we can conclude that if there is a base class named Product, we can derive the Beverage, Chocolate, Biscuit, etc. classes from it and can implement the specific attributes of these derived classes in them.

Let’s derive and use the Beverage class in code:

Get hands-on with 1200+ tech skills courses.