Inheritance reflects the relationship between classes.
Many things in the world share commonalities. The common part is abstracted as the base class for deriving other classes, which improvesCodeThe reusability makes the code structure clear and easy to read, and it is easy to expand and maintain the code.
C # inheritance can only inherit from one base class, which is different from C ++ inheritance.
The inheritance of C # is passed, that is, B inherits from a and c inherits from B, then C has all the features of.
The inheritance of C # is implicitly public.
If a base class constructor is not displayed in the constructor of the derived class, the compiler automatically inserts a call to the default constructor of the base class before executing the code in the constructor of the derived class, if the base class does not have a default constructor, compilation errors may occur.
For example, the common characteristics of animals include mouth, eyes, and noses. They can move and eat.
So define the base class (including the commonality of animals)
Public ClassAnimal {
......
}
When defining specific animals, you can inherit from the base class animal. Instead of redefining these basic features, you just need to define your own unique features.
Example: Dog
Public ClassDog: Animal
{
// The Compiler automatically inserts a call to the default constructor of the base class before executing the code in the constructor of the derived class.
Public StringBark; // the call of a dog
}
Public ClassDog: Animal {
// Display the call to a base class constructor In the constructor of the derived class
PublicDog ()
:Base(){
}
Public StringBark;
}
Note:
The value of a derived class can be assigned to the Base class, but the value of a base class cannot be assigned to the derived class, because the base class cannot be converted to a derived class.The base class only contains some features of the derived class.
Animal animal = new dog ();Correct
Dog dog = new animal ();Error