C has three characteristics of object oriented: encapsulation inheritance and polymorphism

  • 2021-09-11 21:04:25
  • OfStack

Object-oriented programming has three characteristics: encapsulation, inheritance and polymorphism. Object-oriented programming manages complex things according to the characteristics of the real world, abstracts them into objects, has its own state and behavior, and completes tasks by responding to messages. This programming method provides very powerful diversity, greatly increases the opportunity of code reuse, increases the speed of program development, and wraps the independent and special program code, so that modifying some program codes will not affect other parts of the program.

Step 1 Package

Each object contains all the information it needs to operate. It encapsulates the external interface that only exposes the code unit, while hiding its concrete implementation and trying not to expose the code to the outside world. There are many advantages in using packaging. From a design point of view, packaging can shield some important information. For example, people who use computers only need to know how to use computers, and they don't need to know how to realize these functions; For security reasons, Encapsulation makes modifications to code safer and easier, The encapsulation clearly points out which attributes and methods are externally accessible, so that when the code of this class needs to be adjusted, as long as the public attributes and the parameters and return value types of the public methods remain unchanged, the class can be modified freely without affecting other parts of the program; Encapsulation also avoids the problem of naming conflicts. Encapsulation has the function of isolation. Different classes can have methods and properties with the same name without confusion, and can also reduce coupling.

2. Succession

Inheritance can use all the functionality of an existing class and extend it without having to rewrite the original class. Classes generated by inheritance are called derived classes or subclasses, while inherited classes are called base classes or superclasses or parent classes. Inheritance means that a type is derived from a base type, it has all the member fields and functions of the base type, and its subclass is an extension of the parent class; Interface inheritance means that a type inherits only the signature of the function and does not inherit any implementation code. Inheritance divides the hierarchy of classes. It can also be said that inheritance is a grouping of classes. Parent classes represent abstract classes and more commonly used classes, while subclasses represent more specific and detailed classes; Inheritance is an important means to realize code reuse and expansion. The so-called abstract class refers to a class that is related to concrete matters, but only expresses the whole rather than concrete concepts. For example, shapes include squares, rectangles, circles, etc. At this time, shapes are an abstract concept, which is equivalent to a parent class, while squares, rectangles and circles are concrete shapes, which are equivalent to subclasses.

3. Polymorphism

Polymorphism refers to the coexistence of different methods with the same name in a program, which is mainly realized by covering the methods of the parent class by subclasses. In this way, objects of different classes can complete specific functions with the same name, but the specific implementation methods can be different. For example, shapes include squares, rectangles, circles, etc. Each shape has an area and perimeter, but different shapes have different methods to calculate the area and perimeter.

Here is an example to illustrate encapsulation, inheritance and polymorphism:

The base class of this example is the shape mentioned when describing the concept above. Shape is the base class, and this base class is an abstract concept, not a concrete one, so it is an abstract class. This class contains attribute shape names, methods for outputting shape perimeter and area, and abstract methods for calculating shape perimeter and area:


  /// <summary>
  ///  Shape base class 
  /// </summary>
  public abstract class Shape
  {
    /// <summary> 
    ///  Shape name 
    /// </summary>
    public string ShapeName { get; private set; }

    public Shape(string shapeName)
    {
      ShapeName = shapeName;
    }

    /// <summary>
    ///  Output shape perimeter 
    /// </summary>
    public virtual void PrintPerimeter(double perimeter)
    {
      Console.WriteLine(ShapeName + " Perimeter: " + perimeter);
    }

    /// <summary>
    ///  Output shape area 
    /// </summary>
    public virtual void PrintArea(double area)
    {
      Console.WriteLine(ShapeName + " Area: " + area);
    }

    /// <summary>
    ///  Calculate shape perimeter 
    /// </summary>
    /// <returns></returns>
    public abstract double CalculatePerimeter();

    /// <summary>
    ///  Calculate shape area 
    /// </summary>
    /// <returns></returns>
    public abstract double CalculateArea();
  }

Let's look at the specific subclass. The subclass is circle, which contains the attribute radius and the method of calculating perimeter and area:


  /// <summary>
  ///  Circle 
  /// </summary>
  public class Circle : Shape
  {
    /// <summary>
    ///  The radius of a circle 
    /// </summary>
    public double R { get; set; }

    public Circle()
      : base("Circle")
    {
      this.R = 0;
    }

    /// <summary>
    ///  Circumference of a circle 
    /// </summary>
    /// <returns></returns>
    public override double CalculatePerimeter()
    {
      return 2 * Math.PI * R;
    }

    /// <summary>
    ///  Area of a circle 
    /// </summary>
    /// <returns></returns>
    public override double CalculateArea()
    {
      return Math.PI * R * R;
    }
  }

Let's look at rectangles, including attribute height and width, and the method of calculating perimeter and area:


public class Rectangle : Shape
  {
    /// <summary>
    ///  The length of a rectangle 
    /// </summary>
    public double Width { get; set; }

    /// <summary>
    ///  The height of a rectangle 
    /// </summary>
    public double Height { get; set; }

    public Rectangle()
      : base("Rectangle")
    {
      Width = 0;
      Height = 0;
    }

    /// <summary>
    ///  The perimeter of a rectangle 
    /// </summary>
    /// <returns></returns>
    public override double CalculatePerimeter()
    {
      return (Width + Height) * 2;
    }

    /// <summary>
    ///  The area of a rectangle 
    /// </summary>
    /// <returns></returns>
    public override double CalculateArea()
    {
      return Width * Height;
    }
  }

Here is the code to call:


Circle circle = new Circle();
circle.R = 20;

Square square = new Square();
square.Edge = 10;

Rectangle rectangle = new Rectangle();
rectangle.Width = 20;
rectangle.Height = 30;

//  Assigning a subclass to a parent class can better reflect polymorphism 
IList<Shape> shapeList = new List<Shape>();
shapeList.Add(circle);
shapeList.Add(square);
shapeList.Add(rectangle);

foreach (var shape in shapeList)
{
  shape.PrintPerimeter(shape.CalculatePerimeter());
  shape.PrintArea(shape.CalculateArea());
}

In this example, the method of outputting the perimeter and area of the shape is not very useful, because the concrete implementation of the method is relatively simple, and it will be very useful if it is a complex method. For example, if you want to realize the drag function, every shape can be dragged, and the drag method of each shape will be one, but it is not as simple as output if you want to realize the drag function. At this time, the subclass can inherit the method of the parent class and call it directly.


Related articles: