c# abstract class (abstract)

Overview:

An abstract class in C# is a special type of class that cannot be instantiated and can only be inherited. Abstract classes are used to provide a shared base class that defines the signatures of some methods and properties, but has no concrete implementation. These methods and properties can be implemented in derived classes.

The main purpose of using abstract classes is to achieve code reuse and modularization. Abstract classes can define some common methods and properties, while derived classes are responsible for the specific implementation. A derived class must implement all abstract members in an abstract class, otherwise the derived class must also be declared as an abstract class.

detail:

1. Abstract methods must be defined in abstract classes.
2. Abstract methods only have the definition of the method, no specific implementation, and the method body is omitted.
3. Non-abstract methods can also be defined in abstract classes.
4. Abstract classes cannot be instantiated through new. Abstract classes can be used as base classes. The implemented subclasses must override the abstract methods in the abstract class.
5. Many times, some methods in the abstract parent class cannot define specific implementations, and they must be defined in subclasses to implement these methods.

abstract class Animal
{
    
    
    public abstract void Sound();  // 抽象方法

    public void Eat()  // 普通方法
    {
    
    
        Console.WriteLine("Animal is eating");
    }
}

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

class Cat : Animal
{
    
    
    public override void Sound()
    {
    
    
        Console.WriteLine("Cat is meowing");
    }
}

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Animal dog = new Dog();
        Animal cat = new Cat();

        dog.Sound();  // 输出 "Dog is barking"
        cat.Sound();  // 输出 "Cat is meowing"

        dog.Eat();  // 输出 "Animal is eating"
        cat.Eat();  // 输出 "Animal is eating"
    }
}

In the above example, the Animal class is an abstract class, which defines an abstract method Sound and a common method Eat. The Dog class and the Cat class inherit the Animal class and implement the Sound method. In the Main method, we create instances of Dog and Cat and call their Sound and Eat methods.

One of the benefits of an abstract class is that it can provide a shared base class for defining some common behaviors and properties. In this way, we can use abstract classes to uniformly handle some operations that have nothing to do with specific derived classes, thereby achieving code reuse and modularization.

Guess you like

Origin blog.csdn.net/qq_41942413/article/details/132611098