[C# Basic Intensive Lecture] Inheritance, Encapsulation, Polymorphism

insert image description here

Inheritance, Encapsulation and Polymorphism are the three core concepts in object-oriented programming, which form the basis of object-oriented programming and help create more modular, extensible and maintainable code . These three concepts are widely used in C# and other object-oriented programming languages. This article will explain in detail the meaning, characteristics, functions and applications of these three concepts in C#.

1. The concept and characteristics of inheritance

Inheritance is an important relationship in object-oriented programming, which allows a class (subclass, derived class) to inherit the properties and methods of another class (parent class, base class). Through inheritance, subclasses can reuse the code of the parent class, and can add, modify or override specific behaviors on this basis. Inheritance is represented by symbols in C# :.

Inherited Features:

  • Code reuse: Inheritance allows subclasses to reuse the code of the parent class, avoiding writing the same code repeatedly.
  • Derivation and extension: subclasses can be extended on the basis of the parent class, adding new properties and methods to achieve new functions.
  • Hierarchy: The inheritance relationship can form a hierarchy of classes, making the code more organized, easier to understand and maintain.
  • Polymorphism support: Inheritance is the basis of polymorphism. Subclass objects can be used to rewrite parent class methods to achieve different behaviors of different objects.

Here is a simple inheritance example:

class Animal
{
    
    
    public void Eat()
    {
    
    
        Console.WriteLine("Animal is eating.");
    }
}

class Dog : Animal
{
    
    
    public void Bark()
    {
    
    
        Console.WriteLine("Dog is barking.");
    }
}

In the above code, we defined a Animalparent class named and a Dogsubclass named . DogA class inherits the methods Animalof the class Eatand adds its own Barkmethods.

2. The concept and characteristics of packaging

Encapsulation is an important principle of object-oriented programming, which refers to hiding the internal data and implementation details of a class, and only exposing the necessary interfaces for external access. Encapsulation is achieved through access modifiers, such as public, private, protectedetc.

Features of the package:

  • Information hiding: encapsulation hides the internal implementation details of the class, and the outside can only access the properties and methods of the class through the interface, and does not care about the implementation details.
  • Security enhancement: By restricting external access, unreasonable modification and operation can be prevented, and the security of the code is improved.
  • Ease of maintenance: Encapsulation can separate the implementation details of the code from the external interface, making the code more modular and easy to maintain and upgrade.

Here is a simple package example:

class BankAccount
{
    
    
    private double balance;

    public void Deposit(double amount)
    {
    
    
        if (amount > 0)
        {
    
    
            balance += amount;
        }
    }

    public double GetBalance()
    {
    
    
        return balance;
    }
}

In the above code, we defined a BankAccountclass named , where balancethe member variables are declared private and can only be accessed through Depositthe and methods.GetBalance

3. The concept and characteristics of polymorphism

Polymorphism is an important concept in object-oriented programming, which allows objects of different classes to exhibit different behaviors in response to the same message. Polymorphism is achieved through method rewriting and base class references pointing to derived class objects.

Polymorphic features:

  • Unified interface: Polymorphism allows the use of the same interface to call objects of different classes, providing a unified calling method.
  • Code reuse: Polymorphism allows different classes to share the same interface and method name through method rewriting, reducing duplication of code.
  • Dynamic binding: polymorphic method calls are determined dynamically at runtime, rather than fixed at compile time, making the program more flexible.

Here is a simple polymorphic example:

class Shape
{
    
    
    public virtual void Draw()
    {
    
    
        Console.WriteLine("Drawing a shape.");
    }
}

class Circle : Shape
{
    
    
    public override void Draw()
    {
    
    
        Console.WriteLine("Drawing a circle.");
    }
}

class Square : Shape
{
    
    
    public override void Draw()
    {
    
    
        Console.WriteLine("Drawing a square.");
    }
}

In the above code, we defined a base class Shape, and two derived classes Circleand Square. Through polymorphism, we can use the same method name Drawto invoke different behaviors of different classes.

4. Application of Inheritance, Encapsulation and Polymorphism in C Sharp

inherited application

  • Code reuse and modularization: Inheritance allows subclasses to reuse the code of the parent class, thereby avoiding repeated writing of the same code and making the code more modular.
  • Extended functions: Subclasses can be extended on the basis of the parent class, adding new properties and methods, and implementing new functions, thereby improving the scalability of the code.

packaged application

  • Data protection and access control: encapsulation can hide the internal data of the class, only expose the necessary interfaces, protect the data from external access and modification, and improve the security of the code.
  • Interface simplification: Encapsulation can hide complex internal implementation details and provide a more concise external interface, so that users do not need to understand the internal complex logic.

polymorphic application

  • Code uniformity: Polymorphism allows the use of the same interface to handle different types of objects, providing a unified calling method, making the code clearer and more concise.
  • Extensibility: On the basis of polymorphism, new classes can be easily extended to implement new functions without modifying existing codes.
  • Substitutability: Polymorphism allows base class references to point to derived class objects, thereby achieving interface substitutability and making code more flexible.

5. The relationship and trade-offs of inheritance, encapsulation and polymorphism

Inheritance, encapsulation, and polymorphism are the three pillars of object-oriented programming. There is a close relationship between them, and a trade-off needs to be made when using them.

  • Inheritance and encapsulation: Inheritance can cause the implementation details of the parent class to be exposed to subclasses. Therefore, when designing the parent class, it is necessary to distinguish the public interface from the internal implementation to maintain the principle of encapsulation.

  • Inheritance and polymorphism: Inheritance provides the basis for polymorphism. By rewriting the methods of the parent class, subclasses can achieve different behaviors. At the same time, excessive inheritance levels may also lead to complex inheritance relationships and affect code maintainability.

  • Encapsulation and polymorphism: Encapsulation provides a clear external interface, and polymorphism implements different behaviors through this interface. Encapsulation protects the internal implementation details so that polymorphic changes do not affect the external interface.

6. Summary

Inheritance, encapsulation, and polymorphism are core object-oriented programming concepts that help create more modular, extensible, and maintainable code. Inheritance allows subclasses to inherit the properties and methods of the parent class to achieve code reuse and function expansion. Encapsulation hides the internal implementation details of the class, provides external access through the interface, and improves the security and maintainability of the code. Polymorphism allows objects of different classes to respond to the same message, exhibit different behaviors, and provide a more flexible calling method. These three concepts are widely used in C#, and you will be able to write more elegant and robust object-oriented programs by deeply understanding their meaning and application. At the same time, when using these concepts, you need to weigh the relationship between them to ensure that the design and implementation of the code achieve the best results.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132257829