[C#] Inheritance – Three Pillars of OOP (2)

This is the second article of the Three Pillars of OOP. This time, let’s look at the second pillar – Inheritance.

 

1. Reusing Code

When you define a new class, inheritance allows you to reuse the functionalities of existing classes. There are 2 ways to reuse existing classes in most OOP languages.

  • Inheritance (is-a relationship): extends the base class by inheriting the functionalities into the derived class
  • Composition (has-a relationship): rather than establishes parent/child relationship between classes, includes the reference to the object as a member variable in your class

Which type of the code reuse you choose is, well, ” Use your common sense”.

You have an Animal class and want to create a Lion class. A lion is an animal so it is logical that the Lion class  inherits from the Animal class. Meanwhile, you have a Leg class and want to use it in the Lion class. In this case, a lion has legs. So include a leg object (or 4 leg objects) in a Lion.

public class Animal { }
public class Lion : Animal // A lion is an animal
{
  Leg[] legs = new Legs[4]; // a lion has four legs.
}

 

2. C# Inheritance Features

  • A derived class is a specialization of the base class
  • A derived class implicitly gains all the members of the base class, except for its constructors and destructors.
  • A derived class can be inherited from only one base class. In C#, multiple inheritance is not allowed.
  • Structs do not support inheritance.
  • If you do not specify the base class in the class declaration, the class will be inherited from “System.Object” class automatically.

 

3.Access Modifiers

Please read my another post – (Access Modifiers) , which explains this topic in more detail.

 

4. Constructors in the base class

You can use the “base” keyword to call the different Constructor in the base class. If you do not specify the base() call in the derived class’s constructor, the base class’s parameterless constructor is called.

Please refer to my previous post – (Constructors) for more information regarding constructors.

 

5. Abstract Classes

  • Make the class “abstract” in order to prevent direct instantiation of a class
  • An abstract class does not need to include abstract methods
  • If a class contains an abstract member, the class must be declared as abstract
public abstract class Animal {}

 

6. Sealed Classes

A class can prevent other classes from inheriting from it by declaring itself as “sealed“.

public sealed class Lion : Animal { }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s