In-depth analysis of C # Inheritance Mechanism

Source: Internet
Author: User

1. inherit basic knowledge


In order to improve the reusability and scalability of software modules, so as to improve the efficiency of software development, we always hope to use the development achievements of our predecessors or ourselves, at the same time, we hope that we can have enough flexibility in our own development process, so we don't need to stick to Reusable Modules. C # This fully object-oriented programming language provides two important features-inheritance of inheritance and polymorphism.


Inheritance is one of the main features of object-oriented programming. It allows you to reuse code and save time for programming. Inheritance establishes an intersection between classes so that instances of the newly defined Derived classes can inherit the features and capabilities of the existing base classes, you can also add new features or modify existing features to create a new class level.


In the real world, many entities are not isolated from each other. They often share the same characteristics and there are inherent differences. People can use hierarchies to describe the similarities and differences between these entities.



Figure 1 class diagram


Reflects the derivative relationship of transportation tools. Entities at the highest level often have the most general and common features. things at the lower level are more specific, and the lower layer contains the features at the upper layer. The relationship between them is the relationship between the base class and the derived class.


In order to use software language to model the hierarchy in the real world, object-oriented programming technology introduces the concept of inheritance. When a class is derived from another class, the derived class inherits the feature from the base class. A derived class can also be used as the base class of other classes. A multi-level class derived from a base class forms a class hierarchy.


Note: in C #, a derived class can only inherit from one class. This is because in C ++, a class derived from multiple classes is not required in most cases. Deriving a class from multiple base classes often causes many problems, thus offsetting the advantages of this flexibility.
In C #, the derived class inherits members from its direct base class: Methods, domains, attributes, events, and index indicators. Apart from constructors and destructor, the derived class implicitly inherits all the members of the direct base class. See the following example:
Using System;
Class Vehicle // defines the Vehicle class
{
Protected int wheels; // Public Member: Number of wheels
Protected float weight; // protected member: weight
Public Vehicle (){;}
Public Vehicle (int w, float g ){
Wheels = w;
Weight = g;
}
Public void Speak (){
Console. WriteLine ("the number of wheels of a vehicle can be changed! ");
}
};
Class Car: Vehicle // defines the Car class: inherited from the Car class
{
Int passengers; // Private member: Number of passengers
Public Car (int w, float g, int p): base (w, g)
{
Wheels = w;
Weight = g;
Passengers = p;
}
}


As the basis class, Vehicle reflects the public nature of the "Automobile" entity: cars have wheels and weights. The Car class inherits these attributes of Vehicle and adds its own features: it can carry passengers.






Ii. Inheritance in C # complies with the following rules:


1. inheritance can be passed. If C is derived from B and B is derived from A, C not only inherits the members declared in B, but also the Members in. The Object class is the base class of all classes.


2. The derived class should be an extension of the base class. You can add new members to a derived class, but cannot remove the inherited member definitions.


3. constructor and destructor cannot be inherited. Other members can be inherited regardless of their access methods. The access method of the members in the base class can only determine whether the derived class can access them.


4. If a derived class defines a new member with the same name as the inherited member, it can overwrite the inherited member. But this is not because the derived class deletes these Members, but cannot access these members any more.


5. A class can define virtual methods, virtual attributes, and virtual index indicators. Its Derived classes can overload these members, so that the class can display polymorphism.


6. A derived class can only inherit from one class, and multiple inheritance can be achieved through Lu.


The following code is an example of subclass inheriting the parent class:



Using System;
Public class ParentClass
{
Public ParentClass ()
{Console. WriteLine ("parent class constructor. ");}
Public void print ()
{Console. WriteLine ("Im a Parent Class. ");}
}
Public class ChildClass: ParentClass
{
Public ChildClass ()
{Console. WriteLine ("subclass constructor. ");}
Public static void Main (){
ChildClass child = new ChildClass ();
Child. print ();
}
}


Program running output:


Parent class constructor. Subclass constructor. Im a Parent Class.


The above class is named ParentClass, and the class used in the main function is named ChildClass. To do this, create a child class ChildClass that uses the existing Code of the parent class ParentClass.


1. ParentClass is the base class of ChildClass.


This is done by specifying the following in the ChildClass class: "public class ChildClass: ParentClass ". After the identifier of a derived class, use the Semicolon ":" to indicate that the identifier is a base class. C # only supports single inheritance. Therefore, you can only specify one base class.


2. The function of ChildClass is almost equivalent to ParentClass.


Therefore, we can also say that ChildClass is "ParentClass. In the Main () method of ChildClass, this is verified by calling the result of the print () method. This subclass does not have its own print () method. It uses the print () method in ParentClass. The third row in the output result can be verified.


3. The base class is automatically initialized before the class is initialized. The constructor of the ParentClass class is executed before the constructor of the ChildClass class.





3. Access and hide base class members


(1) Access Base Class Members


Access the members of the base class using the base Keyword:


Call methods that have been overwritten by other methods on the base class.
Specify the base class constructor to call when creating a derived class instance.
Base Class access can only be performed in constructors, instance methods, or instance attribute accessors.
It is incorrect to use the base keyword in a static method.


Example: In the following program, the class "Person" and the derived class "Employee" have a method named Getinfo. You can use the base keyword to call the Getinfo method on the base class from the derived class.



Using System;
Public class Person
{
Protected string ssn = "111-222-333-444 ";
Protected string name = "James ";
Public virtual void GetInfo (){
Console. WriteLine ("name: {0}", name );
Console. WriteLine ("No.: {0}", ssn );
}
}
Class Employee: Person
{
Public string id = "ABC567EFG23267 ";
Public override void GetInfo (){
// Call the GetInfo method of the base class:
Base. GetInfo ();
Console. WriteLine ("member ID: {0}", id );
}
}
Class TestClass {
Public static void Main (){
Employee E = new Employee ();
E. GetInfo ();
}
}


Program running output:


Name: James
No.: 111-222-333-444
Member ID: ABC567EFG23267
Example: A derived class communicates with a base class.



Using System;
Public class Parent
{
String parentString;
Public Parent ()
{Console. WriteLine ("Parent Constructor .");}
Public Parent (string myString ){
ParentString = myString;
Console. WriteLine (parentString );
}
Public void print ()
{Console. WriteLine ("Im a Parent Class .");}
}
Public class Child: Parent
{
Public Child (): base ("From Derived ")
{Console. WriteLine ("Child Constructor .");}
Public void print (){
Base. print ();
Console. WriteLine ("Im a Child Class .");
}
Public static void Main (){
Child child = new Child ();
Child. print ();
(Parent) child). print ();
}
}


Program running output:


From Derived
Child Constructor.
Im a Parent Class.
Im a Child Class.
Im a Parent Class.


Note:


1. The derived class can communicate with the base class during initialization.


The code above demonstrates how to implement communication with the base class in the constructor definition of the subclass. Semicolon ":" and keyword base are used to call constructors of the base class with corresponding parameters. In the output result, the first line indicates that the base class constructor is called first. In fact, the parameter is the string "From Derived ".


2. Sometimes, the existing methods of the base class are intended to be redefined.


The Child class can redefine the implementation of the print () method. The print () method of Child overwrites the print method in Parent. The result is: the print method in the Parent class is not called unless otherwise specified.


3. In the print () method of the Child class, we specify that the print () method in the Parent class is called.


The method name is preceded by "base". Once the "base" keyword is used, you can access members with public or protected permissions of the base class. The execution result of the print () method in the Child class appears the third and fourth rows above.


4. Another way to access base class members is through explicit type conversion.


This is the last statement in the Main () method of the Child class. Remember: A derived class is a special case of its base class. This fact tells us that we can convert the data type in the derived class to make it an instance of the base class. The last line of the above Code actually executes the print () method in the Parent class.





2) Hide base class members


Think about it. If all the classes can be inherited

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.