Inheritance and polymorphism in C #

inherit

Inheritance is to realize the reuse of programs, and transfer the functions of the parent class to the child class, so the child class can save the work of redefinition.

This concept is also closely related to object-oriented. Object oriented is to abstract objects, and different abstraction levels will get different classes. For example, college students - Students - people - animals - biology is a process of continuous abstraction. The more abstract, the more general and less unique attributes; The more abstract, the more concrete, and the richer the attributes; Moreover, the attributes of the lower layer must include the attributes of the upper layer. College students must have students' attributes, so c# the inheritance is to use the attributes of the upper layer to the lower layer. The program can be used as follows:

  public class Person
    {
        public string Name;
        public int Age;
        public void Eat()
        {
            //eat
        }
        public void Move()
        {
            //move
        }
    }
    public class Student : Person
    {
        public string StudentNumber;
        public string Grade;
        public void Study()
        {
            //study
        }
    }

    //test
    public class test
    {
        private void main()
        {
            Student stu = new Student();
            stu.StudentNumber = "202201220301";
            stu.Study();
            //In addition to using the properties and methods in the student class, you can also directly use the properties and methods in the parent class, as follows:
            stu.Name = "Lisa";
            stu.Move();
        }
    }

Some characteristics of inheritance:

  • Transitivity: you can pass inheritance. For example, C inherits from B, B inherits from A, and C also inherits from A;
  • Singleness: a derived class can only inherit from one base class, not from multiple base classes, but can inherit from multiple base classes through the interface;
  • Affected by the access modifier, the base class defined using private cannot be inherited;
  • The constructor in the base class cannot be inherited directly. Use base inheritance;
  • The base class object can reference the derived class object, that is, the instance of the derived class can be assigned to the instance of the base class, and the base class can use the methods and properties of the derived class.

Polymorphism

Polymorphism refers to the same method name, which is handled differently according to different input parameters. This is c# a very common way. For example, when calling a system method, it indicates that there are several overloaded methods. That method is a polymorphic method.

There are three conditions for polymorphism:

  • Overloading is to take the same method name but use different types of parameters or different numbers of parameters to automatically form an overload, but different return types do not form an overload.
            public static void Write(string moduleName, string message, Exception ex)
            {
                log4net.ILog log = log4net.LogManager.GetLogger(moduleName);
                if (ex != null)
                {
                    log.Error(message + ";" + ex.Message, ex);
                }
                if (!string.IsNullOrEmpty(message))
                {
                    log.Info(message);
                }
                log = null;
            }
    
            public static void Write(string moduleName, Exception ex)
            {
                //By using moduleName twice, the current method only needs two parameters to realize polymorphism
                Write(moduleName, moduleName, ex);
            }
  • Override, closely related to inheritance, is to override the methods of the base class in the derived class. Generally, a virtual method is declared in the base class with the keyword virtual, and then overridden in the derived class, so that different functions can be realized in different derived classes. For example, animals have the method of eating (), but the chicken's eating () is pecking, the dog's eating () is biting, and the snake's eating () is swallowing. Overriding eating () in a derived class can realize the above expression. Rewriting is an important means to realize polymorphism.

        //Methods in base classes
        public  virtual void  Display()       //The base class Person is defined as a virtual method, using the virtual keyword
        {
              Console.WriteLine("{0}yes{1}Sex, age{2}", this._name, this._gender, this._age);                  
        }
    
        //Methods in derived classes
        public override void Display()                 //Override the Display method in the base class
        {
              Console.WriteLine("This is a student:");    //Write new code in a derived class
              base.Display();                        //Call the Display method of the base class to Display
        }
  • Hiding is basically the same as overriding, except that the methods in the base class are not defined with the virtual keyword, and the derived classes can only use new to hide the methods of the base class.

      //Code immediately above
      public new void Display(string no)   //Hide base class with new
      {
              Console.WriteLine("This is a student:");
              base.Display();              //Call the Display method of the base class
              Console .WriteLine ("The student number is:{0}",no);
      }

Keywords: C# Back-end

Added by Nytemare on Mon, 24 Jan 2022 09:02:01 +0200