Inheritance notes for object oriented programming mechanisms in C

  • 2020-12-18 01:54:18
  • OfStack

Inheritance reflects the relationships between classes.

Many things in the world have commonness. The common part is abstract as the base class, which is used to derive other classes. In this way, the code reusability is improved, the structure of the code is clear and easy to read, and the extension and maintenance of the code are easy.

Inheritance of C# can only be inherited from one base class, which is different from inheritance of C++.

The inheritance of C# is transitive, that is, B inherits from A and C inherits from B, then C has all the characteristics of A.

The inheritance of C# is implicitly public's.

If a call to a base class constructor is not shown in the derived class constructor, the compiler automatically inserts a call to the default constructor of the base class before executing the code in the derived class constructor, causing a compilation error if the base class does not have a default constructor.

Example: Animals have a mouth, eyes, nose, can move, can eat

So define the base class (including the commonality of animals)


public class Animal {
      ......       
    }

When you redefine specific animals, you can inherit from the base class Animal. You don't have to redefine these basic characteristics, just define your own unique characteristics.

For example: Dog


public class Dog:Animal
    {  
        // The compiler automatically inserts the default constructor for the base class 1 The code in the derived class constructor is then executed
        public string Bark;// The dog barked
    }


public class Dog : Animal {
// Displays the call in the derived class constructor 1 Six base class constructors
        public Dog()
            : base() {
        }
        public string Bark;
    }


Note:

You can assign the value of a derived class to a base class, but you cannot assign the value of a derived class to a derived class, because a base class cannot be converted to a derived class, and the base class contains only a subset of the derived class's properties.

Animal animal=new Dog(); The correct

Dog dog=new Animal (); error


Related articles: