C# study notes - encapsulation, inheritance, polymorphism

1. Packaging

  • Encapsulation is defined as "enclosing one or more items in a physical or logical package". In object-oriented programming methodology, encapsulation is to prevent access to implementation details;
  • Abstraction and encapsulation are related features of object-oriented programming. Abstraction allows visualization of related information, and encapsulation enables developers to achieve the desired level of abstraction ;
  • C# encapsulation sets the user's access rights according to specific needs, and implements it through access modifiers. An access modifier defines the scope and visibility of a class member;
  • Access modifiers supported by C# :
    Note : A: parent class   ~ B: Son   ~ C: Wife   ~ D: illegitimate child (not at home)
    public: all objects can be accessed; (everyone on earth knows)
    private: the object itself can be accessed inside the object; (privacy, only A himself knows)
    protected: only objects of this type and their subtypes Can be accessed; (A, B, D all know, wife C does not know)
    internal: objects in the same assembly can be accessed; (A, B, C know, illegitimate child D does not know)
    protected internal: access is limited to the current assembly or A type derived from a contained class. (A, B, C, D all know, others don't)

insert image description here

2. Inheritance

  • The inheritance class derives the public and protected characteristics and behaviors of the base class (parent class, superclass), and can arbitrarily add and modify the characteristics and behaviors of the subclass
  • Inheritance is achieved by adding a colon (:) after the name of the derived class (subclass), followed by the name of the base class (parent class)
  • The derived class can call the constructor (constructor) of the base class by adding a colon after the derived class parameter list and calling the base class constructor with the keyword base
  • Syntax:
    access level    ~~   class    ~~   Derived class name: base class name
    {       ~~~~~
         class member...
    }
 class People
 {
    
    
     /// <summary>
     /// 姓名
     /// </summary>
     public string Name {
    
     get; set; }  //has a
     private int top;

	 public People(int top)
	{
    
    
		this.top=top;
	}

     //仅仅本"家族"使用
     protected int a;
 }

 class Teacher:People   //  is a 
 {
    
    
     
     /// <summary>
     /// 工资
     /// </summary>
     public int Salary {
    
     get; set; }
     private int left;//新的成员
     public Teacher(int top,int left):base(top)//base调用基类构造函数,先走基类,再走派生类
     {
    
    
     	this.left = left;
     }

 }

 static void Main(string[] args)
 {
    
    
     //继承    
     //父类  只能使用  父类成员
     People person1 = new People();

     //子类  除了可以使用子类成员  还可以使用  父类成员
     Student stu01 = new Student();
     stu01.Name =""; 

     //父类型的引用  指向  子类的对象
     //只能使用父类成员
     People person2 = new Student();
     person2.Name = "";
     //如果需要访问该子类成员,需要强制类型转换
     Student stu02 = (Student)person2;
     //异常
     //Teacher tea01 = (Teacher)person2;
     //如果转换失败,不会抛出异常
     Teacher tea01 = person2 as Teacher;
     if(tea01 !=null)
         tea01.Salary = 100;
 }

Note:
1. The access modifier protected can make the (private) method in the parent class be called in the subclass instead of being used by other external classes; 2. The
role of base:
1> access members of the base class
2> access the base class constructor of

  • Liskov conversion
    ---- subclass can be assigned to the parent class (if the parent class is needed, then a subclass can be used instead)
    ---- if the parent class contains the subclass object, then the parent class can be assigned Class coercion into the "corresponding" subclass object

  • new keyword
    ---- 1. Create an object
    ---- 2. Hide members with the same name inherited from the parent class. The hidden consequence is that the subclass cannot call the members of the parent class.

Three, polymorphism

  • Polymorphism is the ability to have multiple different manifestations or morphologies of the same behavior. In the object-oriented programming paradigm, polymorphism is often expressed as "one interface, multiple functions".
  • Polymorphism can be dynamic or static. In static polymorphism , the response of a function occurs at compile time. In dynamic polymorphism , the response of a function happens at runtime.
  • Design idea: only objects (not procedures) know how to perform a specific operation , and use commonality to promote code reuse by specifying the general way of these operations
  • Three ways to achieve polymorphism:
    1. Abstract class
    2. Virtual method
    3. Interface
  • If the method name in the subclass is the same as the method name of the parent class , the subclass will hide the method of the parent class by default. There are two solutions:
    1. Use the new keyword
    2. Use virtual methods
  • When the method in the parent class does not know how to implement it , you can consider writing the parent class as an abstract class and writing the method as an abstract method

1. Static polymorphism

At compile time, the linking mechanism of functions and objects is called early binding, also known as static binding. C# provides two techniques to achieve static polymorphism, namely:

  • function overloading
  • operator overloading

2. Dynamic polymorphism

Dynamic polymorphism is achieved through abstract classes and virtual methods .

1>Abstract class

  • C# allows the use of the keyword abstract to create an abstract class, which is used to provide the implementation of some classes of the interface.
  • Syntax:
    access modifier   ~  abstract   ~   class   ~  Class name (note: the first two can be changed in order)
  • Abstract method syntax:
    abstract   ~ access modifier   ~ return value type   ~ Method name (note: the first two can be changed in order)

Notice:

  • The abstract class establishes the basis of the derived class, but cannot instantiate an abstract class object (cannot new itself);
  • If any method of the class is marked as abstract, then the entire class should be marked as abstract, and the abstract method has no implementation part of the method ;
  • Marking a method of an abstract class as abstract means that each derived class that inherits from the base class must implement its own abstract method . If the derived class does not implement an abstract method, then the derived class must also be an abstract class and cannot be instantiated;
  • The opposite of an abstract class is a sealed class, and the sealed class modifier: sealed. Function: It is forbidden for any class to derive from this class (but the sealed class can inherit other classes), and the string class is a sealed class;
  • If there are parameters in the abstract method of the parent class, then the subclass inheriting the abstract parent class must also pass in the corresponding parameters when rewriting the parent class method; if there is a return value in the abstract method of the abstract parent class, then the subclass When rewriting this abstract method, the return value should also be passed.
using System;
namespace PolymorphismApplication
{
    
    
   abstract class Shape//抽象类
   {
    
    
       abstract public int area();//基类的抽象方法
   }
   class Rectangle:Shape
   {
    
    
      //字段
      private int length;
      private int width;
      //构造函数
      public Rectangle( int a=0, int b=0)
      {
    
    
         length = a;
         width = b;
      }
      public override int area ()//派生类的抽象方法
      {
    
    
         Console.WriteLine("Rectangle 类的面积:");
         return (width * length);
      }
   }

   class RectangleTester
   {
    
    
      static void Main(string[] args)
      {
    
    
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("面积: {0}",a);
         Console.ReadKey();
      }
   }
}

2> virtual method

  • When there is a function defined in a class that needs to be implemented in an inherited class, a virtual method can be used ;
  • The keyword of the virtual method is virtual , and the virtual method can have different implementations in different inherited classes;
  • virtual can be used for properties and methods
  • Syntax:
    access modifier   ~ virtual   ~  return value type   ~ method name
  • In the derived class method, use the keyword override to override the virtual method in the base class ;
  • Steps to use virtual methods:
    1. Mark the method of the parent class as virtual, indicating that the method of the parent class can be overridden by the subclass
    2. Mark the method of the subclass as override, indicating that the method of the parent class is overridden
using System;

namespace Day09
{
    
    
    /// <summary>
    /// 多态
    /// </summary>
    /// 
    class Animal
    {
    
    
        public string Name {
    
     get; set; }
        public virtual void Shout() {
    
     Console.WriteLine("未知叫声"); }//虚方法
    }

    class Dog:Animal
    {
    
    
        public override void Shout() {
    
     Console.WriteLine(base.Name + ":汪汪"); }//复写虚方法
    }
    class Dog1:Animal
    {
    
    
        public new void Shout() {
    
     Console.WriteLine(base.Name + ":汪汪"); }//不进行复写,使用自己方法
    }

    class Cat:Animal
    {
    
    
        public override void Shout() {
    
     Console.WriteLine(base.Name + ":喵喵"); }//复写虚方法
    }

    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //Dog dog = new Dog() { Name = "小黑" };
            //dog.Shout();

            Animal animal = new Cat() {
    
     Name = "小黑" };//类型转换
            animal.Shout();

        }
    }
}

Note:
1. Use the flag new to indicate that the method is not an override method of the virtual method in the base class

Four. Summary

  • The inheritance class derives the public and protected characteristics and behaviors of the base class, and can add and modify its own characteristics and behaviors arbitrarily;
  • Inheritance is achieved by adding a colon after the derived class name, followed by the base class name;
  • The derived class can call the constructor of the base class by adding a colon after the parameter list of the derived class and calling the base class constructor with the keyword base;
  • The method marked as virtual in the base class can be overridden by the derived class, and the keyword override needs to be used in the method definition of the derived class. This is the key to achieving polymorphism: when a virtual method is called on a derived class, the derived behavior is invoked;
  • Derived classes can break the polymorphism of derived methods, but they must be identified with the keyword new;
  • A method identified as abstract has no method implementation, but simply provides a method name and signature that derived classes must override. Any class that contains an abstract method is an abstract class, and such a class cannot be instantiated;
  • Any class marked as sealed cannot be derived;
  • Abstract classes cannot be instantiated, and abstract methods have no method body;
  • If the method in the parent class has a default implementation, and the parent class needs to be instantiated, then you can consider defining the parent class as an ordinary class and use virtual methods to achieve polymorphism; if the method in the parent class does not have a default implementation, The parent class does not need to be instantiated either, so the class can be defined as an abstract class.

Guess you like

Origin blog.csdn.net/Lcl_huolitianji/article/details/119743215