C#. Inheritance. Basic concepts. Advantages and disadvantages. General form. The simplest examples. Access modifier protected




Inheritance. Basic concepts. Advantages and disadvantages. General form. The simplest examples. Access modifier protected


Contents


Search other websites:

1. What is inheritance in programming?

Inheritance is one of the principles of object-oriented programming, which enables the class to use the program code of another (base) class, supplementing it with its own implementation details. In other words, during inheritance, a new (derived) class is obtained that contains the program code of the base class with its own usage features. Inheritance belongs to the is-a type of relationship between classes. Inheritance creates a specialized version of an existing class.

 

2. The advantages of using inheritance in programs

Proper use of the inheritance mechanism provides the following related benefits:

  • efficient construction of complex class hierarchies with the possibility of their convenient modification. The operation of classes in the hierarchy can be changed by adding new inherited classes in the right place in the hierarchy;
  • reuse of previously written code with its further modification to the task being performed. In turn, the newly created code can also be used on the underlying class hierarchies;
  • convenience in maintaining (supplementing) the program code by introducing new classes with new features;
  • reducing the number of logical errors in the development of complex software systems. Reusable code is more often tested, which means less chance of errors in it;
  • ease of coordination different parts of the program code by using interfaces. If two classes are inherited from a common descendant, the behavior of these classes will be the same in all cases. This statement comes out of the requirement that similar objects should have similar behavior. The use of interfaces itself determines the similarity of the behavior of objects;
  • creation of code libraries that can be used and supplemented by your own developments;
  • the ability to implement well-known design patterns to build flexible code that does not change previous designs;
  • taking advantage of polymorphism is impossible without inheritance. Thanks to polymorphism, the principle is ensured: one interface – several implementations;
  • providing research programming (rapid prototyping). Such programming is used in cases where the goals and requirements of the software system at the beginning are vague. First, a layout of the structure is created, but this layout is gradually improved by inheriting the previous one. The process continues until the desired result;
  • a better understanding of the structure of the software system by the programmer due to the natural representation of the inheritance mechanism. If you try to use other principles when building complex hierarchies, this can greatly complicate the understanding of the entire task and lead to an increase in the number of errors.

 

3. Disadvantages of inheritance

When using inheritance in programs, the following disadvantages were noticed:

  • it is not possible to modify an inherited implementation at runtime;
  • the base class partially defines the physical representation of its subclasses. There is a strong connection between the implementations of the base and derived classes, which is undesirable in solving some problems;
  • low execution speed. The speed of execution of general-purpose program code is lower than in the case of using specialized code that is written specifically for this task. However, this drawback can be corrected by examining and optimizing code that takes a considerable amount of execution time;
  • large dimension of the programs through the use of general purpose libraries. If for some task we develop highly specialized program code, then this code will occupy less memory than general purpose code;
  • increasing the complexity of the program in the case of incorrect or incompetent use of inheritance. A programmer must be able to use inheritance correctly when building class hierarchies. Otherwise, this will lead to more confusion of the program code, and, as a result, an increase in errors;
  • the difficulty of assimilating by beginners programmers the basics of building programs that use heredity. You need to be able to isolate something in common, then this general detail and code correctly. However, this lack of a conditional, as it depends on the programmer experience.

 



4. What is a base class? What is a derived class?

A base class is a class whose program code is used in inherited (derived) classes. A derived class is a class that uses the program code of a base class and modifies (extends) it to fit its needs. In other programming languages (for example, Java), the base class is also called the superclass, and the derived class is called the subclass.

 

5. The syntax of inheritance in the case of two classes. General form

If one class inherits another base class, then the general declaration form of such a class is as follows:

class derived_class : base_class
{
  // class body
  // ...
}

where

  • derived_class – name of the derived class;
  • base_class – name of the base class;

For example.

// base class
class Base
{
  // fields and methods of the class
  // ...
}

// class inherited from class Base
class Derived : Base
{
  // fields and methods of the class
  // ...
}

In the above example, Base is the base class, Derived is the class that inherits the capabilities of the Base class. In the Derived class, all elements (fields, properties, methods, indexers, etc.) that are described with the protected, public, and internal access modifiers are directly accessible. In turn, the Derived class can be the base for another lower-level class.

 

6. Access to elements of the base class that are declared with access modifiers private, protected, public, internal, protected internal

In a derived class, base class elements that are declared with protected, public, internal, and protected internal access modifiers are available. All elements of the base class that are declared with the private modifier are not available in the derived class.

Example. The example demonstrates the effect of access modifiers on access to elements of the base and derived classes.

using System;
namespace ConsoleApp1
{
  // Base class
  class Base
  {
    // internal class of the class Base
    private int private_Item;
    protected int protected_Item;
    internal int internal_Item;
    protected internal int protIntern_Item;
    public int public_Item;
  }

  // Derived class from the Base class
  class Derived : Base
  {
    // method that modifies the fields of the Base class
    void Method()
    {
      protected_Item = 10;
      internal_Item = 20;
      protIntern_Item = 30;
      public_Item = 40;
      // private_item = 50; - error, item is inaccessible
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Access to an instance of the class
      // 1. Base class
      // 1.1. Create an instance of Base class
      Base bs = new Base();

      // 1.2. Access to the fields of bs instance
      // bs.private_Item = 10; - Access is forbidden
      // bs.protected_Item = 20; - Access is forbidden
      bs.internal_Item = 30; // internal - is allowed
      bs.public_Item = 40; // public - is allowed
      bs.protIntern_Item = 50; // protected internal - разрешен

      // 2. Derived class - access to fields of the class Base
      // 2.1. Create an instance of Derived class
      Derived dr = new Derived();
      // dr.private_Item - private-access is forbidden
      // dr.protected_Item - protected-access is forbidden
      dr.internal_Item = 30; // internal - is allowed
      dr.public_Item = 40; // public - is allowed
      dr.protIntern_Item = 50; // protected internal - is allowed
    }
  }
}

 

7. How many classes can be inherited from a base class at the same time?

The C# programming language does not support multiple inheritance (unlike the C++ language). Only one class can be inherited from a particular class at a time. However, a class can inherit any number of interfaces. For more information about interfaces can be read here.

 

8. Features of using protected and protected internal access modifiers. Example

Each item of the class can have different access levels: private, public, protected, internal, protected internal. If the program uses the inheritance mechanism, the protected and protected internal access modifiers deserve special attention.

If a class item (field, method, property, etc.) is implemented with the protected access modifier, then the following rules are executed to it:

  • an item is available within the class in which it is declared, as well as in inherited classes;
  • item is not available from class instance.

The protected internal access modifier combines the restriction of the protected modifier and the internal modifier (see example). Two cases are possible here:

  1. The situation when a class with a protected internal element and an instantiated instance of this class are in the same assembly. In this case, access from the class instance to the protected internal element is (extension of the internal keyword). There is also access from a derived class (extension of the protected keyword).
  2. The situation when a class with a protected internal element is declared in one assembly and an instance of this class is created in another assembly. In this case, the instance does not have access to the protected internal element (internal constraint). But you can create a derived class and from this class access the protected internal element (extension protected).

Example. Demonstration of the use of access modifiers on the example of three classes A, B, C.

using System;

namespace ConsoleApp1
{
  // Base class
  class A
  {
    // Protected fields of class A
    protected int a;
    protected internal int aa;
  }

  // Derived class B
  class B : A
  {
    // Protected fields of class B
    protected int b;
    protected internal int bb;

    public void Method()
    {
      // There is access to protected
      // and protected internal items of class A.
      a = 25;
      aa = 30;
    }
  }

  // Derived class C
  class C : B
  {
    // Protected fields of class C
    protected int c;
    protected internal int cc;

    public void Method()
    {
      // There is access to protected
      // and protected internal items of classes A, B
      a = 10;
      aa = 20;
      b = 30;
      bb = 40;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // No access from class instances
      // to protected items
      A objA = new A(); // The instance of class A
      B objB = new B();
      C objC = new C();

      // objA.a = 30; - no access
      // objB.a = 20; - no access
      // objB.b = 20; - no access
      // objC.a = 20; - no access
      // objC.b = 20; - no access
      // objC.c = 20; - no access

      // However, there is access to the protected internal instances of classes A, B, C,
      // since in this example the classes A, B, C
      // and their instances objA, objB, objC are declared in the same assembly
      objA.aa = 40;
      objB.aa = 50;
      objB.bb = 50;
      objC.aa = 10;
      objC.bb = 20;
      objC.cc = 30;
    }
  }
}

 


Related topics

 


 

0
fb-share-icon20