The old man died and said to the three sons, "You can inherit three things from me: Money, credit card, and knowledge. You can choose ."
The eldest son said, "I want money ."
The second said, "I want a credit card ."
The three sons said, "I want knowledge ."
The old man said, "money is in a credit card, and the password of a credit card is in your brother. You can get money only when you know the password! Knowledge is money ."
1. Why is there inheritance?
Class B contains all or part of the code with class A. If you use the copy and paste method, the amount of code is increased and the readability is reduced.
To create a class that can reuse methods, attributes, events, and variables of other classes.
A is called a parent class, base class, or superclass, and B is called a subclass.
2. What is the essential meaning of inheritance?
Just like property inheritance, inheritance inherits all the members of a class to another class. For example, Class B inherits from Class.
So, all the members of Class A (data, methods, attributes, etc.) are elements of Class B, because it inherits.
However, inheritance is one thing. It is another thing to directly access these members. Don't be confused by what follows cannot access the private in the parent class.
Because after inheriting all the data, access control is a key point.
3. All inherited members
In Class B, there are not only inherited Class A members, but also Class B members. Such a big family will affect each other and play a good show.
For example, in Class B, the functions of a member of Class A are enhanced, displayed, or overwritten, or hidden.
In access control and function addition and subtraction, it is often said that a role in the parent class is not a role inherited by Class A in Class B.
4. Create a base class
A parent has a child. If it is not explicitly specified that the class cannot be used as the base class, it can be derived from the subclass.
Add class: 1. Project> Add class. (We recommend that you use a separate file for reuse)
2. directly use the keyword class to add.
Public Class Person Public Property Name() As String Public Property BirthDate() As DateEnd Class
After the creation, right-click the solution and choose View class diagram to view the members of the UML diagram display class.
5. Create a subclass
Create a class in the same way as 4. to indicate that this is a subclass of a certain class, add the keyword "inherits" to the class.
In the following example, the class is inherited from person.
Public Class Employee Inherits Person Public Property HireDate() As Date Public Property Salary() As DoubleEnd Class
If you use inherits to inherit the class outside the current project, you must specify the namespace including the class, or use imports statements to introduce the referenced namespace at the top of the class.
The preceding example shows that the employee class includes all the functions and interfaces of the person class.
So we can use:
Public Class Form1 Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click Dim emp As New Employee With emp .Name = "Fred" .BirthDate = #1/1/1960# .HireDate = #1/1/1980# .Salary = 30000 txtName.Text = .Name txtBirthDate.Text = Format(.BirthDate, "Short date") txtHireDate.Text = Format(.HireDate, "Short date") txtSalary.Text = Format(.Salary, "$0.00") End With End SubEnd Class
Although the employee does not see the member name and birthdate, it does inherit from the person, so it has such a member, so it can be used.
6. overload in subclass
Although there is a name and birthdate method after employee inheritance, we can still define our own name and birthdate methods. This type is called overload.
The existing methods in the overloaded base class are essentially the same as the conventional methods in the heavy load (I .e., the same name and different parameters)
The difference is that overloads must be added to a base class member for heavy load.
Public Enum nametype 'enumeration informal = 1 formal = 2end enumpublic class employee inherits person public property hiredate () as date public property salary () as double public mnames as new generic. dictionary (of nametype, string) 'generic, public overloads property name (byval type as nametype) set that stores keys/Values) as string 'required overlaods and the name of person is overloaded get'. Otherwise, the name return mnames (type) end get set (value as string) If mnames in person will be masked. contains (type) Then mnames. item (type) = value else mnames. add (type, value) end if end set end propertyend class
Note: 1. If the sub-class has the same name and same parameter, it will be hidden (shadows). In this example, the same method of the base class will "disappear ". Later.
2. nametype is an enumeration type, and mnames is a collection object used to store creation/value. Similar to an array, mnames indexes are used to store search values.
In the following example, different values are displayed by calling the name attribute.
Public class form1 private sub btnok_click (sender as object, e as eventargs) handles btnok. click dim EMP as new employee () with EMP. name = "Fred ". name (nametype. formal) = "mr. frederick "'added, officially named, reload. name (nametype. informal) = "Freddy" 'new addition, informal name, reload. birthdate = #1/1/1960 #. hiredate = #1/1/1980 #. salary = 30000 txtname. TEXT =. name txtformal. TEXT =. name (nametype. formal) 'reload txtinformal. TEXT =. name (nametype. informal) 'reload txtbirthdate. TEXT = format (. birthdate, "short date") txthiredate. TEXT = format (. hiredate, "short date") txtsalary. TEXT = format (. salary, "$0.00") end with end subend class
The result is as follows:
Now, we can view the class diagram again:
Note: 1. Overloads can be omitted if multiple methods in the same class are overloaded. However, if overloads is written for a method, all the other overload operations must be added.
2. Overloads must be added for overloading between different classes (parent classes and child classes.
7. Rewrite
Overload is the addition and expansion of interfaces.
Instead of retaining the existing functions, replace or replace the functions of the base class.
By default, unspecified members of the base class are not allowed to be overwritten. In order to override, The overridable keyword must be used to indicate that the base class member can be rewritten.
(In essence, it is to create a virtual function table and check the C ++ virtual function in detail)
For example, to change the birthdate function in the subclass (check whether it is 16 years old), first specify in the base class that the birthdate can be rewritten by the quilt class (rewritten)
Public class person public overridable property birthdate () as date 'only indicates that it can be rewritten public property name () as stringend class
Add the following data and attributes to the subclass:
Overrides is used to indicate that this method is used to override the subclass:
Private mbirthdate as date Public overridable property birthdate () as date 'indicates to override get return mbirthdate end get set (value as date) If datediff (dateinterval. year, value, now)> 16 then mbirthdate = value else throw new aggresponexception ("at least 16") 'New Structure error message object end if end set end property
Note: an error message object is created. An exception message is thrown when the condition is met.
8. mybase
After rewriting, the base class cannot be referenced again because of this method. For example, a method with the same name of the base class cannot be referenced after rewriting.
In this case, mybase is used to forcibly reference methods from the base class. Whether or not it is overloaded or not, it will use the base class members without errors in one step.
Public Overrides Property BirthDate() As Date Get Return MyBase.BirthDate End Get Set(value As Date) If DateDiff(DateInterval.Year, value, Now) >= 16 Then MyBase.BirthDate = value Else Throw New AggregateException("at least 16") End If End Set End Property
9. Virtual Methods
A virtual method is a method that can be rewritten and replaced by a subclass. For example, rewriting birthdate is an example of a virtual method.
According to C ++'s personal conjecture:
Each variable has its own memory address, so that the program can accurately find the value of the variable.
Similarly, each method (function) block also has its own memory start address, so that the program can accurately call the method.
The method in the object is called based on the method address in its memory, so that the corresponding method can be used accurately.
Generally, the subclass has its own method address, and the base class has its own method address, which corresponds to the query call.
However,
In case of rewriting, a node is added to the method address list to point to a virtual function table.
Once overridabel is used, a virtual function table is created and all overridable items are listed in a list.
Once overrides is used, the original method address is replaced in the virtual function table. Call the corresponding method.
Can be detailed here to learn: http://blog.csdn.net/haoel/article/details/1948051/
As a result, the virtual method gives us a variety of States. The variable type is not the deciding factor, but the actual reference object type is the most important.
In the following example, the variable type person references the object type person and does not have ambiguity:
Public class form1 private sub btnok_click (sender as object, e as eventargs) handles btnok. click dim EMP as new person () with EMP 'EMP is both a person variable and a reference to person (the two are the same without ambiguity ). name = "Fred ". birthdate = #1/1/2000 # txtname. TEXT =. name txtbirthdate. TEXT = format (. birthdate, "short date") end with end subend class
In the following example, the variable type is "employee", and the referenced object type is "employee", and there is no ambiguity:
Private sub btnok_click (sender as object, e as eventargs) handles btnok. click dim EMP as person EMP = new employee () 'EMP is of the person type, but it references the employee with EMP'. Therefore, the final employee is used. The following is the employee used. name = "Fred ". birthdate = #1/1/2000 # '. Therefore, txtname is verified in the employee ID. TEXT =. name txtbirthdate. TEXT = format (. birthdate, "short date") end with end sub
Example: The variable type is "person", the referenced object type is "employee", and is overwritten.
Public class form1 private sub btnok_click (sender as object, e as eventargs) handles btnok. click dim EMP as person EMP = new employee () with EMP. name = "Fred ". birthdate = #1/1/2000 # End with displayperson (EMP) 'although it is of the person type, therefore, the following call verifies birthdate end sub private sub displayperson (byval theperson as person) with theperson txtname. TEXT =. name txtbirthdate. TEXT = format (. birthdate, "short date") end with end subend class
Two important rules are obtained:
1. variables of the base class type can always store references of their subclass objects.
2. in virtual methods, the object data type is the most important, and the Data Type of the variable is not the deciding factor.
10. Rewrite the overloaded method.
Reload is to retain the original function and extend its function.
Rewrite is to rewrite or replace the original function.
Sometimes we need to do it at the same time, that is, rewrite and reload. Rewrite is for the base class, and overload is for the subclass, and the direction is different,
This creates a strange concept of "override methods that have been overloaded.
In the subclass, the name () method in the base class is overloaded first, but it wants to rewrite the name () method of the base class.
Therefore, overrides is used to rewrite the name in the base class. After rewriting, it is found that the name (nametype) already exists in the subclass, so overloads must be added before it, which indicates that this
The relationship between name and the name with parameters in the subclass is overloaded.
Public Class person Private mName As String Public Overridable Property Name() As String Get Return mName End Get Set(value As String) mName = value End Set End PropertyEnd ClassPublic Enum NameType informal = 1 formal = 2 normal = 3End EnumPublic Class customer Inherits person Private mNames As New Generic.Dictionary(Of NameType, String) Public Overloads Property Name(ByVal type As NameType) As String Get Return mNames(type) End Get Set(value As String) If mNames.ContainsKey(type) Then mNames.Item(type) = value Else mNames.Add(type, value) End If If type = NameType.normal Then MyBase.Name = value End If End Set End Property Public Overloads Overrides Property Name() As String Get Return mNames(NameType.normal) End Get Set(value As String) mNames(NameType.normal) = value End Set End PropertyEnd Class
NoteThat you are using bothOverridesKeyword (to indicate that you are overriding the name method from the base class)
AndOverloadsKeyword (to indicate that you are overloading this method in the subclass ).
Note: The overrides keyword indicates that it is used to override the name () method in the base class (person ).
The overloads keyword indicates that the overload is the name () method of the sub-class (employee), because the method Signature Name (nametype) is already in place ).
(From right to left)
For compatibility, normal is added to the enumeration in the above example, and the write to the base class is added to the parameter name:
Public overloads property name (byval type as nametype) as string get return mnames (type) end get set (value as string) If mnames. containskey (type) Then 'Here, the value mnames in employ is updated. item (type) = value else mnames. add (type, value) end if type = nametype. normal then 'Here, the value in person is updated. In this way, both mybase. Name = value end if end set end property are updated.
11. Shadows)
In fact, hiding should be learned before rewriting.
Hiding is like a scope. global variables are hidden by local variables with the same name during the process.
If the base class design is incorrect and the source code cannot be obtained, or the base class is applicable in most cases, it must be rewritten in special cases.
The method in the base class is not allowed to be overwritten (no overridable) during design. What should I do if I want to "Rewrite" the method in the subclass?
Shadows can be used to hide methods of the same name of the base class.
Simply put:
Overwrite is an overridable rewrite.
Hiding is a method that forcibly modifies the base class without permission.
If the overrides keyword is not used to declare a method, it is a non-virtual method, rather than a virtual method, which cannot be overwritten or replaced by the quilt class.
Hiding is like this. It needs to override non-Virtual Methods, whether or not they are declared with overridable, and it ignores the rules.
Therefore, hiding the proportion of data is more bloody. If the rewriting is a legal and compliant judicial person, hiding the content is a lawless robbery.
Therefore, the rule is hidden and broken. developers of the base class are always very careful when marking the method or not marking the overridable. Make sure that the method is overwritten in the subclass.
Ensure that the base class can continue to work normally. Shadows often does not mark overridable and does not want to rewrite the rule.
Normally, it is expected that the subclass object "employee" is not only the employee object, but also the person object (because employee is the Child class of person ),
However, the use of shadows fundamentally changes the functions of the employee, so it is no longer a person object, this method essentially deviates from normal expectations will
Errors are thrown and the code is difficult to understand and maintain.
So the hidden method is a dangerous method !!!
Let's look at the example. First define a non-virtual method in person-read-only age so that it is intentionally negative, so that it can be corrected in the subclass:
Public class person public overridable property birthdate () as date Public overridable property name () as string public readonly Property Age () as integer get return CINT (datediff (dateinterval. year, now, birthdate) 'intentionally sets the age to negative end get end propertyend class
How to hide the base class in the subclass employee:
Public shadows readonly Property Age () as integer 'shadows can be saved. If this parameter is omitted, a warning is displayed. If the get' function with the same name is omitted, the return CINT (datediff (dateinterval. year, birthdate, now) end get end property
Note that shadows can be omitted, but the IDE will warn you that it is best to add shadows.
Hiding occurs when the method signature is the same.
Then let's look at several calls to illustrate the differences with rewriting.
Rewriting mainly depends on the type of actually used objects.
While hiding is the opposite, it only looks at the initial type of the variable.
The following variable type is person, so the age in person is used, so it is negative:
The following variable type is employee, so the age is hidden and the positive value is used in the sub-class employee:
The following variable type is person, so the age of the base class is used, so it is a negative value:
Shadows is a monster that can be changed to read-only:
Public shadows Property Age () as integer 'change read-only to get return CINT (datediff (dateinterval. year, birthdate, now) end get set (byval value as integer) birthdate = dateadd (dateinterval. year,-value, now) end set end property
In this way, unexpected problems occur during use. The following variable type is person, so age can only be read-only, so an error is prompted:
Change the variable type to employee:
In more extreme cases, the Shadows monster can also convert methods into instance variables or attributes into methods.
For example, in the sub-class employee, change the age to the following:
Public shadows age as string
This indicates that when shadows hides a base class element, the Child class will change its sacrifice or scope.
When it comes to scope, hiding actually works:
Local variables hide global variables to make them invalid during the process:
In the base class and subclass, the principle is the same:
The scope of the data type description of the variable. The actual object data type only indicates its value. So hiding occurs like a scope.
Under the above rule, hiding always happens on the "Shortest Path". For example, in the subclass domain, it should be accessing the subclass, however, because this element in the subclass is private and cannot be accessed, the nearest scope will be found up. As follows:
The preceding three scopes are divided based on the variable type,
First is the largest and can call itself, so it is the firstclass
Second, the display of this class is hidden. Unfortunately, it is private and cannot be accessed. Therefore, the shortest path to the top is firstclass, so it is displayed.
Third is the smallest, which hides the first and second above and can be called, so it is displayed as thirdclass. (If this parameter is set to private, first is called)
Public class form1 private sub button#click (sender as object, e as eventargs) handles button1.click dim A as new useclasses. showz () end subend classpublic class basecls public Z as integer = 100 'declares the end classpublic class dervcls inherits basecls public shadows Z as string = "*"' to activate and hide end classpublic class useclasses dim basobj as basecls = new dervcls () dim derobj as dervcls = new dervcls () Public sub showz () msgbox ("accessed through base class:" & basobj. z) 'base class variable, So 100 msgbox ("accessed through derived class:" & derobj. z) 'subclass variable, so * end subend class
12. Hierarchy of Inheritance
(1) Multi-Inheritance
That is, a subclass inherits two or more base classes at the same time.
. NET Framework does not support multi-inheritance, so VB.net does not support it.
However, you can use multiple interfaces to obtain functions similar to multi-inheritance.
(2) Multi-Level inheritance
That is, subclass becomes the base class of another class.
So that all the members of the upper-level class are inherited to the class. It is greatly extended.