C # Three object-oriented features: encapsulation, inheritance, and Polymorphism,

Source: Internet
Author: User

C # Three object-oriented features: encapsulation, inheritance, and Polymorphism,

Object-Oriented Programming has three features: encapsulation, inheritance, and polymorphism. It manages complex things according to the characteristics of the real world, abstracts them into objects, and has its own State and behavior, the task is completed by responding to the message. This programming method provides a very strong diversity, greatly increases the chance of code reuse, increases the speed of program development, and packs specially crafted program code with independence, modifying some program code does not affect other parts of the program.

1. Encapsulation

Each object contains all the information required for its operations. The encapsulation only discloses the external interface of the Code unit, hides its specific implementation, and tries its best not to disclose the code. Encapsulation has many advantages. From the design point of view, encapsulation can shield some important information externally. For example, a computer user only needs to know how to use the computer, you don't need to know how these functions are implemented. In terms of security, encapsulation makes code modifications safer and easier. encapsulation clearly specifies which attributes and methods are externally accessible, in this way, when you need to adjust the code of this class, as long as the public attributes remain unchanged and the parameters and return values of the public method remain unchanged, you can modify this class as much as possible, but it does not affect other parts of the program. encapsulation also avoids naming conflicts. Encapsulation has an isolation function. Different classes can have methods and attributes with the same name, but will not be confused, it can also reduce coupling.

2. Inheritance

Inheritance can use all the functions of the existing class and extend these functions without re-writing the original class. Classes generated by inheritance are called Derived classes or subclasses, while inherited classes are called base classes, superclasses, or parent classes. Inheritance indicates that a type is derived from a base type. It owns all member fields and functions of the base type, and its subclass is an extension of the parent class; interface inheritance means that a type only inherits 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 groups classes. parent classes represent abstract classes and more commonly used classes, while child classes represent more specific classes, more refined classes; inheritance is an important means to achieve code reuse and expansion. Abstract classes refer to classes that are associated with specific items, but only express the whole rather than specific concepts. For example, shapes include squares, rectangles, circles, etc, at this time, shape is an abstract concept, which is equivalent to a parent class, while square, rectangle, and circle are specific shapes, which are equivalent to child classes.

3. Polymorphism

Polymorphism refers to the coexistence of different methods with the same name in the program. It is implemented by overwriting the parent class method by subclass. In this way, objects of different classes can use methods with the same name to complete specific functions, but the specific implementation methods can be different. For example, a shape contains a square, a rectangle, and a circle. Each shape has an area and a perimeter. However, different shapes use different methods to calculate the area and perimeter.

The following example illustrates encapsulation, inheritance, and Polymorphism:

The base class in this example is the shape mentioned in the above description. The shape is the base class, and the base class is an abstract concept, not a specific one. Therefore, it is an abstract class, this class contains the attribute shape name, the output shape circumference and area, and the abstract Method for Calculating the shape circumference 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 the shape perimeter /// </summary> /// <returns> </returns> public abstract double CalculatePerimeter (); /// <summary> /// calculate the shape and area /// </summary> /// <returns> </returns> public abstract double CalculateArea ();}
View Code

Next let's take a look at the specific subclass. The subclass is a circle, including the attribute radius, the calculation cycle, and the area method:

/// <Summary> /// Circle /// </summary> public class Circle: shape {/// <summary> /// radius of the Circle /// </summary> public double R {get; set;} public Circle (): base ("Circle") {this. R = 0 ;}/// <summary> /// circle perimeter /// </summary> /// <returns> </returns> public override double CalculatePerimeter () {return 2 * Math. PI * R ;}/// <summary> // area of the circle /// </summary> /// <returns> </returns> public override double CalculateArea () {return Math. PI * R ;}}
View Code

Let's take a look at the rectangle, including the attribute height and width, the calculation cycle and area:

Public class Rectangle: Shape {// <summary> /// the length of the Rectangle /// </summary> public double Width {get; set ;} /// <summary> /// Height of the Rectangle /// </summary> public double Height {get; set;} public Rectangle (): base ("Rectangle ") {Width = 0; Height = 0 ;} /// <summary> /// rectangular perimeter /// </summary> /// <returns> </returns> public override double CalculatePerimeter () {return (Width + Height) * 2 ;} /// <summary> /// rectangular area /// </summary> /// <returns> </returns> public override double CalculateArea () {return Width * Height ;}}
View Code

The following code is called:

Circle circle = new Circle (); circle. R = 20; Square square = new Square (); square. edge = 10; Rectangle rectangle = new Rectangle (); rectangle. width = 20; rectangle. height = 30; // assign the subclass to the parent class to better reflect the 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 ());}
View Code

In this example, the method for outputting the circumference and area of the shape does not play a major role because the implementation of the method is relatively simple. For example, to implement the drag-and-drop function, every shape can be dragged, and every shape can be dragged in the same way, but to implement the drag-and-drop function is not as easy as the output, in this case, the subclass can inherit the method of the parent class and directly call it.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.