All operations performed almost in Visual Basic are associated with an object. If you first contact object-oriented programming, the following terms and concepts will help you get started.
Class and object words "class" and "objects" are used in large-oriented programming, which is easy to confuse them. In general, "class" is an abstract representation of some content, and "object" is an available example of the content represented by the class. Shared class members are an exception to this rule, which can be used in an instance of the class and a declared object variable for shared class.
Fields, properties, methods, and event classes consist of fields, properties, methods, and events. Fields and properties represent information included in the object. Fields are similar to variables because they can be read or set. For example, if there is an object called Car, you can store its color in a field called Color.
The retrieval and setting methods of the attribute are similar to the field, but the attribute is implemented using the Property Get and the Property SET process, which provides more control over how to set up or return values. The indirect layer between the stored value and the process of using this value helps isolation data and enables you to verify these values before assigning or retrieving values.
Method represents an operation of an object. For example, a Car object can have StartEngine, Drive, and STOP methods. The method is defined by adding a process (SUB routine or function) to the class.
The event is a notification that the object is received from other objects or applications, or the object is transmitted to other objects or applications. Event enable objects to perform operations whenever a particular situation occurs. An event example of a CAR class is Check_Engine event. Because Microsoft Windows is an event-driven operating system, events can be entered from other objects, applications, or user inputs (such as mouse click or buttons).
Package, inheritance, and polymorphism fields, properties, methods, and events are just half the content of the object-oriented programming. Real object-oriented programming requires three characteristics: package, inheritance, and polymorphism.
"Package" means considering a set of related properties, methods, and other members as a unit or object. Objects can control how to change properties and implement methods. For example, an object verifies values before allowing an attribute to change. By hiding the implementation details of the object (a practice called "data hiding"), the package also makes it easier to make changes to the implementation in the future.
"Inherited" describes the ability to create new categories based on existing classes. All properties, methods, and events of the new class inherit the base class, and other properties and methods can be used to customize the new class. For example, you can create a new class named TRUCK based on a CAR class. The TRUCK class inherits the Color property from the CAR class, and there can be other properties, such as FourWheelDrive.
"Polymorphism" means having multiple interchangeable classes, even if each class implements the same properties or methods in different ways. Polymorphism is the essence of object-oriented programming because it allows the same name of the same name, regardless of what type of object is used. For example, assuming a given base class Car, polymorphism allows the programmer to define different StartEngine methods for any number of derived classes. The StarTengine method named DieSelcar can be completely different from the method of the same name in the base class. Other processes or methods can use the StartEngine method of derived class in the same way, regardless of what type of Car objects are used.
Overload, rewriting and hide can store information in the object using fields and properties. Although the field and attributes are almost unable to distinguish from the client application perspective, they declare their way in the class. The property uses the Property process to control how to set up or return values, and the field is just a common variable disclosed in the class.
Add a field to the class
Declare a public variable in the class definition, as shown in the code: Class thisclass public thisfield AS STRINGEND CLASS Add attribute to class
A local variable is declared in the class to store the attribute value. This step is required because the attribute does not assign any storage area itself. To protect their values, the variables used to store attribute values should be declared as private. The modifier (such as public and shared) as a modified declaration as needed. Use the Property keyword declare the property name and declare the data type of the property store and the returned data. Define the GET and SET property procedures in the property definition. The GET property process is used to return the value of the attribute value, which is basically equivalent to the function in the syntax. They do not accept parameters, which can be used to return the value of private local variables for storing attribute values in the class. The set attribute process is used to set the value of the attribute, which has a parameter (commonly referred to as value), which is the same as the data type of the attribute itself. Whenever the property value changes, Value is passed to the SET property process, which can be verified in the process and store it in a local variable. Terminate the GET and SET attribute procedures using the END GET and END SET statements as needed. Use the End Property statement to terminate the property block. Note If you are working under the Visual Studio integration development environment (IDE), you can indicate that it removes the empty GET and SET property procedures. Type the Property PropName As DataType (where PROPNAME is the property name, DATATYPE is a specific data type, such as Integer, the corresponding property process will appear in the code editor. The following examples in the class declaration attribute: Class ThisClass Private m_PropVal As String Public Property One () As String Get Return m_PropVal '. Return the value stored in the local variable' Optionally, you can use the syntax One = PropVal to return ' The Property Value. End Get Set (Byval Value As String) M_PropVal = Value 'Store The Value IN A Local Variable. End End PropertyEnd Class When you create an instance of thisclass and set the value of the one property, the set property process is called and This value is passed in the Value parameter, which is stored in a local variable named M_PropVal. When searching this attribute value, call the GET property process as the function, and return the value stored in the local variable m_propval.
Properties and attributes
You can store information in the object using properties and fields. Property Use properties to control how to set up or return values, and fields are just public variables. The property process is a code block declared in the attribute definition so that you can execute the code when setting or retrieving attribute values. Visual Basic .NET has two types of property procedures: get attribute procedures are used to retrieve attribute values; set attribute processes are used to assign values to attributes. For example, the property of the storage bank account balance may use the code during the get attribute to log in the interest and check the service fee before returning the available balance. The SET property process for the available balance provides verification code to prevent incorrect update balance. In short, the property process allows object protection and verification of your own data.
Only read and write attributes
Most attributes have two attribute processes that get and set so that you can read and modify the stored value at the same time. However, you can use the ReadOnly or Writeonly modifier to limit read or modifications to attributes. Read-only properties cannot have a set property process, which can be used to need public but not modified items. For example, read-only properties can be used to provide the speed of the computer processor. Only write attributes cannot have a Get property process, which can be used to store but not disclose other objects. For example, only write properties can be used to store passwords. Note Earlier Version of Visual Basic supports the use of the list property when assigning objects to properties. Visual Basic .NET eliminates the need for the LET property process, as you can process object assignments like any any kind of assignment.
The property process and field properties and fields can store and retrieve information in the object. Their similarity makes it difficult to determine which is better programming in a given situation.
Use the properties process in the following cases:
It is necessary to control the time and mode of the setting or retrieve value. Attributes have a fixed set of values that need to be verified. Set values can cause certain detemeable changes in the object state (such as a visible attribute). Setting attributes When you change the value of other internal variables or other properties. A set of steps must be performed before setting or retrieve properties. Use fields in the following situations:
The value is the type of auto-authentication. For example, if you assign a value other than true or false to the Boolean variable, an error or automatic data conversion occurs. Any value within the support range supported within the data type is valid. Many attributes of the Single or Double type belong to this situation. The property is a String data type and is when there is no constraint for the size or value of the string.
The method of class method class is the SUB or FUNCTION process declared in this class. For example, to create a WITHDRAWAL method for classes called Account, you can add this public function to this class module:
Public Function WithDrawal (ByVal Amount As Decimal, _ ByVal TransactionCode As Byte) As Double 'Add code here to perform the withdrawal,' return a transaction code, 'or to raise an overdraft error.End Function sharing method sharing method can be directly from the class Variable calls don't have to create instances of this class first. The sharing method is useful when it is not desirable to associate with a particular instance of the class. The sharing method cannot be declared with Overridable, NotOverridable or Mustoverride modifier. The method declared in the module is implicitly shared and cannot explicitly use Shared modifiers.
Example Class Sharclass Shared Sub SharedSub () MessageBox.show ("Shared Method.") End Sub End Class
Sub test () 'Create An Object Variable, but not an instance. DIM S AS ShareClass S.SharedSub' Call The Method.end Sub Protection Implementation Details The Utility Process used inside the class should be declared as private, protected or friend. Accessibility to restrict such methods prevent them from being used by other developers, and allow you to make changes in the case where you do not affect the code of these objects.
The details of the hidden object implementation are on the other hand of "package". The package allows you to improve the performance of the method, or completely changing the way to implement the method, without having to change the code using the method.
The attributes and method properties and methods are implemented as the process of accepting parameters, which they are similar at this point. Typically, the property stores the object's data, and the method is the operation that can be required to be executed. Some of the objects are obviously attribute, such as Name, and some obvious ways, such as Move and Show. In other cases, which type members should be attributes which should be method and is not obvious. For example, the ITEM method of the collection class stores and retrieves data, which can be implemented as an index attribute. On the other hand, it is also reasonable to achieve Item as a method. The attribute syntax and method syntax determine how the way to implement class members is to consider how to use it. Although the syntax from the parameterized property retrieve information is almost the same as the syntax used as a function, the syntax of this value is modified is slightly different. For example, if you implement the members of the class as an attribute, the following syntax description will use it:
ThisObject.thisproperty (index) = NewValue If the class member is implemented as a method, the value to modify must be a parameter. The following code snippet describes equivalent syntax usage:
ThisObject.ThisProperty (Index, NewValue) Error message Select Another factor to consider when you implement class members is that when you are incorrect, you will generate what message will be generated. If someone is inadvertently trying to assign a value for the read-only property, an error message will be returned, which is different from the error message returned by the response to the method of modes. Correctly implemented class members returns an error message that is easier to explain.
The default attribute accepts the properties of the parameters to declare the default properties of the class. "Default Properties" is the properties that Microsoft Visual Basic .NET will use when naming a specific property to an object. Because the default properties make the source code more streamlined by omitting the common property name, the default properties is very useful.
The most suitable as default properties is those acceptable parameters and what you think will be the most commonly used. For example, the item attribute is a good choice for a collection class default attribute because it is often used.
The following rules apply to the default properties:
One type can only have a default attribute, including attributes inherited from the base class. This rule has an exception. The default attribute defined in the base class can be hidden by another default attribute in the derived class. If the default attributes in the base class are hidden in the derived attribute in the derived class, the default properties can be accessed using the default attribute syntax. The default attribute cannot be Shared or Private. If an overload attribute is the default property, all the overload properties of the same name must also specify default. The default attribute must accept at least one parameter. Example The following example declares an attribute containing a string array as a class:
Class Class2 'Define a local variable to store the property value. Private PropertyValues As String ()' Define the default property. Default Public Property Prop1 (ByVal Index As Integer) As String Get Return PropertyValues (Index) End Get Set (ByVal Value As String) If PropertyValues Is Nothing Then 'The array contains Nothing when first accessed. ReDim PropertyValues (0) Else' Re-dimension the array to hold the new element. ReDim Preserve PropertyValues (UBound (PropertyValues) 1) End If PropertyValues (Index = Value End SET End PropertyEnd Class Access Default Properties You can use an abbreviation syntax to access the default properties. For example, the following code snippet uses standard and default attribute syntax: DIM C as new class2 () 'the first two lines of code access a property the standard war.c.prop1 (0) = "Value One"' Property Assignment. Messagebox.show (C.Prop1 (0)) 'Property Retrieval.
'The Following TWo Lines of Code Use Default Property Syntax.c (1) = "Value TWO"' Property Assignment.MessageBox.show (c (1)) 'Property Retrieval. Reserved attributes and method overloads are in a class Create more than one process, instance constructor or attribute with the same name but different parameter types.
The overload is very useful when the object model indicates the same name for the operation on different data types. For example, a class that can be displayed several different data types can have a DISPLAY process similar to:
Overloads Sub Display (ByVal theChar As Char) 'Add code that displays Char data.End SubOverloads Sub Display (ByVal theInteger As Integer)' Add code that displays Integer data.End SubOverloads Sub Display (ByVal theDouble As Double) 'Add code that displays Double Data.end Sub If you do not use overload, even if each process performs the same operation, you also need to create different names for them, as shown below:
Sub DisplayChar (ByVal theChar As Char) 'Add code that displays Char data.End SubSub DisplayInt (ByVal theInteger As Integer)' Add code that displays Integer data.End SubSub DisplayDouble (ByVal theDouble As Double) 'Add code that displays Double data. End Sub Because overload provides a selection of available data types, it makes it easier for properties or methods. For example, you can use the following code line to call the overloaded DISPLAY method: Display ("9" c) 'Call Display with a literal of type char.display (9)' Call Display with a literal of type integer. Display (9.9R) 'Call Display with a literal of type double. When running, Visual Basic .NET calls the correct process based on the data type of the specified parameter.
Pay attention to overload, rewriting, and hidden operations. Similar concepts are easy to confuse. For more information, see Objects in Visual Basic.
Overloading rules use the same name to add two or more attributes or methods to create a heavy-duty member of the class. In addition to overloading derived members, each overload member must have a different list of parameters. When an overloaded attribute or procedure, the following items cannot be used as a distinction feature:
Modifiers applied to members or member parameters, such as ByVal or byref. The return type of the parameter name process is overloaded when the keyword overloads is optional, but if any overload member uses the overloads keyword, all other name overload members must specify the keyword.
Detective classes can be kept inherited with members with the same parameters and parameter types, which is called "hidden by name and signature". If the OverLoads keyword is used when hidden in name and signature, the implementation of the member's derived class is implemented instead of the base class, and all other overloads of the member will be available for instances of the faction.
If an overloads keyword is omitted with a member with the same parameter and a parameter type, the overloads are omitted, and the overload is called "hidden by name". Hide, hide the inheritance implementation of a member, so that all other overloads are not available for instances of the fault and the class derived.
OverLoads and Shadows modifiers cannot be used by the same attribute or method at the same time.
Example The following example creates String or Decimal representation of the USD volume and returns a string containing the sales tax.
Use this example to create an overload method
Open a new project and add a class named TaxClass. Add the following code to the TaxClass class. Public Class TaxClass Overloads Function TaxAmount (ByVal decPrice As Decimal, _ ByVal TaxRate As Single) As String TaxAmount = "Price is a Decimal. Tax is $" & _ (CStr (decPrice * TaxRate)) End Function Overloads Function TaxAmount (ByVal strPrice As string, _ byval Taxrate As Single) AS String Taxamount = "Price Is A String. TAX IS $" & _ CSTR ((CDEC (Strprice) * TaxRate)) End Functionend Class Add the following process to the form. Sub ShowTax () Const TaxRate As Single = 0.08 '8% tax rate Dim strPrice As String = "64.00"' $ 64.00 Purchase as a String. Dim decPrice As Decimal = 64 '$ 64.00 Purchase as a Decimal. Dim aclass As New taxclass () 'Call the same method with two diferent kinds of data. MessageBox.Show (aclass.TaxAmount (strPrice, TaxRate)) MessageBox.Show (aclass.TaxAmount (decPrice, TaxRate)) End Sub add a button to the form, and from the Button1_Click event calls the showTAX process. Run the project and click the button on the form to test the overloading the showTAX process. At runtime, the compiler selects the appropriate overload function that matches the parameters used. When you click this button, first call the pric parameter of the string to be overloaded and display information: "Price is a string.tax is $ 5.12". The second time will use the value of the type Decimal to call Taxamount and display information "Price Is A Decimal.TAX IS $ 5.12". Rewriting properties and methods
Detectively inherit the properties and methods defined in its base class. This is useful because it means that they can be reused when these items are suitable for class you want to use. If the inheritance member cannot be used as it is, you can choose to use the Overrides keyword to define a new implementation, assume that the properties or methods in the base class use the Overridable keyword tag, or to define members in the derived class to hide the member. In fact, members rewritten are often used to achieve polymorphism. For more information on polymorphism, please refer to the polymorphism. The following rules apply to override methods. A member of the marker with an Overridable keyword can only be rewritten. By default, attributes and methods are NotOtherridable. The rewritten member must have the same parameters as those inherited from the base class. Members' new implementation can call the original implementation in the parent class by specifying myBase before the method name. Pay attention to overload, rewriting, and hidden operations. Similar concepts are easy to confuse. For more information, see Objects in Visual Basic. Example assumes that you want to define a class to handle the payroll. You can define a general Payroll class that contains the RunpayRoll method that calculates the normal weekly wage. You can then use the BonusPayroll class when you can use the base class of a more dedicated BonusPayroll class to distribute employee bonuses. BonusPayroll class can inherit and rewrite the PayEmployee method defined in the base class Payroll. The following example defines the base class Payroll and the derived class BonusPayroll, which rewrites the inheritance method PayemPloyee. Process Runpayroll creates a Payroll object and BonusPayRoll object, and then passes it to function PAY, which performs these two object's PayEMPloyee method. Const BonusRate As Decimal = 1.45Const PayRate As Decimal = 14.75Class Payroll Overridable Function PayEmployee (ByVal HoursWorked As Decimal, _ ByVal PayRate As Decimal) As Decimal PayEmployee = HoursWorked * PayRate End FunctionEnd Class
Class BonusPayroll Inherits Payroll Overrides Function PayEmployee (ByVal HoursWorked As Decimal, _ ByVal PayRate As Decimal) As Decimal 'The following code calls the original method in the base' class, and then modifies the returned value. PayEmployee = MyBase.PayEmployee (HoursWorked, PayRate) * Bonusrate End Functionend Class
Sub runpayroll () Dim PayrollItem as payroll = new payroll () Dim bonuspayrollitem as new bonuspayroll () Dim Hoursworked As Decimal = 40
MessageBox.Show ( "Normal pay is:" & _ PayrollItem.PayEmployee (HoursWorked, PayRate)) MessageBox.Show ( "Pay with bonus is:" & _ BonusPayrollItem.PayEmployee (HoursWorked, PayRate)) End Sub modifier can rewrite Use NOTOVERRIDABLE and MUSTOVERRIDE modifiers to control how to retrieve properties and methods in derived classes. NOTOVERRIDABLE modifiers define methods that cannot be rewritten in derived classes. All methods are NOTOVERRIDABLE, unless marked with an Overridable modifier. You can use the NOTOVERRIDABLE modifier when you do not wish to override the Overridden method again in the derived class. The method defined by the Mustoverride modifier is not implemented in the base class, and must be implemented in the derived class. Classes containing the Mustoverride method must use the Mustinherit modifier to tag. Example MustInherit Class BaseClass Public MustOverride Sub aProcedure () End ClassClass DerivedClass Inherits BaseClass Public NotOverridable Overrides Sub aProcedure () 'Override a procedure inherited from the base class' and mark it with the NotOverridable modifier so that' it can not be overridden in classes derived from The Class. End Subend Class provides an ideal method for managing various objects with a collection management object set. You can add and remove objects in a collection, retrieve them according to the index or keys, and use the for Each ... Next statement cycle through items in the collection. However, highly flexibility of the collection may destroy the reliability of the class.
You can use three conventional methods to use collections to implement object management. Consider the organization of widgets and disclose them to the client components. To implement this component using a collection, you can:
In the WidgetRepository class, declare the Widgets variable as a collection and make it a common variable. Enhance your own WidgetScollection class by inheriting the CollectionBase class. Grant a WidgetRepository class a WidgetScollection class attribute. This feature is implemented by writing appropriate classes and methods in the WidgetRepository class. This approach is most useful if you have a collection type function in the class, but you cannot inherit from any set type class. For example, if you want to inherit from other classes other than the collections. A collection of collections can be added to the class to manage objects that may be disclosed by the class. The easiest way to implement this feature is to add a common variable of the type of Collection to the class. Consider the assumption class named WidgetRepository, this type of management and public widgets. You can create a WidgetCollection variable as a collection of widgets, as shown in the example below:
Public Class WidgetRepository Public WidgetCollection As New Collection () 'Insert Code To Implement Additional FunctionAlity.end Class This class There is now a public collection that adds a Widget object to it. But this method has some problems. First, this collection is not a strong type. What happens if the following code will happen? DIM mystring as string = "this is not a widget Object!" WidgetCollection.add (mystring) answer is that it will be added to the collection, even if it is not a Widget object. In fact, any object can be added to the collection, no matter what type. If you will then try to use the for Each ... NEXT statement to handle the widget, the problem occurs, as shown below:
DIM AWIDGET AS WIDGETFOR EACH AWIDGET IN WIDGETCOLLECTION 'INSERT CODE TO Process WidgetsNext In this example, the program triggers ArgumentException at runtime, because one member of the collection is not a widget type.
Another problem involves a member of an open collection. Because the Collection class accepts and returns a member of the Object type, any functionality of the object managed by the collection is not available when the Option StriT statement is ON. To convert the reference to the reference to the appropriate type, you must use the CType function as follows:
DIM MyWidget AS WidgetMyWidget = CType (WidgetCollection (1), Widget) Note that when the option strict is OFF, the implicit conversion is implicit, although the late binding will result in a decline in performance.
If you need to avoid these issues, or more reliable collection of your class, you should consider creating your own collection class using CollectionBase. For more information, see Works: Create your own collection class.
Events and Event Handle The Visual Studio project is easily seen as a process of executing in a series of sequence. In fact, most programs are event-driven, that is, the execution process is determined by an event that occurs in the outside world. The event is a signal that informs the application to have important situations. For example, when a user clicks a control on the form, the form triggers a Click event and calls a process that handles the event. Event also allows communication between different tasks. For example, your application is out of the main program to perform a sorting task. If the user cancels this order, the application can send a cancel event to stop the sorting process. Event Terms and Concepts This section describes the terms and concepts used with events in Visual Basic .NET. Declare events Use the Event keyword in the class, structure, module, and interface internal declaration events, as shown in the following example: Event Anevent (ByVal EventNumber AS Integer) raises event events like an important message that has taken place in the announcement. Broadcasting the behavior of the message triggered an event. In Visual Basic .NET, use the RaiseEvent statement to raise events, as shown in the following example: raiseeevent anevent (eventnumber) must trigger events within the scope of the declaration event. For example, derived classes cannot trigger events inherited from base classes. Event Transmitter Any object that can raise events is an event sender, also known as an event source. Objects, controls, and user-defined objects are event transmitters. The event handler event handler is a process called when the corresponding event occurs. You can use any valid subroutines as an event handler. However, the function cannot be used as an event handler because it cannot return the value to the event source. Visual Basic is named using a standard naming agreement, which combines the name of the event transmitter and event with the next underscore. For example, click Events of Buttton1 buttons should be named sub button1_click. Note It is recommended to use this naming agree to define the event handler of your own event. But this is not a necessary method. You can use any valid subroutines. The associated event and event handler must first use the Handles or AddHandler statement to associate it with the event before the event handler takes effect. The WITHEVENTS statement and the handles clause provide a method of specifying an event handler. The event that WitHevents declares that objects that can be initiated by any subroutine with a Handles clause named this event. Although the Handles clause is a standard method for associated events and event handlers, it is limited to the compiled event and event handler. AddHandler and RemoveHandler statements are more flexible than the Handles clause. They allow the event to be dynamically connected or disconnected at the runtime, and does not require use of WitHevents to declare object variables. In some cases, such as an event associated with a form or control, Visual Basic .NET automatically leads an empty event handler and associates it with an event. For example, when you double-click the command button on the form, Visual Basic .NET creates an empty event handler and a WitHevents variable for the command button, as shown in the following example: Friend WitHevents Button1 As System.Windows.Forms. ButtonProtected Sub Button1_Click (Byval E AS System.EventArgs) Handles Button1.Clickend Sub Interface Overview and class, the interface also defines a range of properties, methods, and events. However, different from the class is that the interface does not provide implementation. They are implemented by classes and are defined from the class as separate entities. The interface represents an agreement that the class that implements the interface must be strictly defined for each aspect of the interface.
With an interface, you can define the functionality as a group of close-related members. The enhancement implementation of the interface can be developed without endangeting the existing code, thereby minimizing compatibility issues. You can also add new features at any time by developing additional interfaces and implementations. Although the interface implementation can evolve, the interface itself cannot be changed once it is published. Changing the published interface will destroy the existing code. If the interface is considered an agreement, it is clear that both parties have their own obligations. The publisher of the interface agrees that the interface is no longer changed, and the implementation of the interface agrees to implement the interface in strict accordance with the design.
Visual Basic .NET previous Visual Basic versions can be used, but they cannot create them directly. Visual Basic .NET allows the true interface to be defined with an interface statement and allow these interfaces to be implemented with an improved version of IMPLEments keywords. Inherited Basics Inherits statements are used to declare new classes based on existing classes (called "base classes") (called "derived class"). Detective classes inherit and expand the properties, methods, events, fields, and constants defined in the base class. The following section describes some inheritance rules, as well as modifiers that can be used to change the class inheritance or inheritance:
By default, all classes are inherited unless marked with a Notinheritable keyword. Categories can inherit from other class in the project, or inheritance from the class of other program collections referenced. Unlike the language that allows multiple inheritance, Visual Basic .NET only allows you to have a single inheritance in the class, that is, it can only have one base class. Although multiple inherits are not allowed in the class, the class "can" implement multiple interfaces, which can effectively achieve the same purpose. To prevent restricted items in the public base class, the access type of the derived class must be limited to its base class or more than its base class. For example, the PUBLIC class cannot inherit the Friend or Private class, and the Friend class cannot inherit the Private class. Inheritance Decorator Visual Basic .NET introduces the following level statements and modifiers to support inheritance:
Inherits Statement - Specifies the base class. Notinheritable modifier - prevents programmers from using this class as base classes. Mustinherit modifier - Specifies that this class is only suitable for use as a base class. Unable to create an instance of the Mustinherit class directly, you can only create the base class instance of the derived class. (Other programming languages, such as C and C #, using the term "abstract class" to describe such classes.) Rewinding attributes and methods in derived classes By default, derived classes from their base class inheritable methods. If inherited attributes or methods need to have different behaviors in the derived class, you can "rewrite" it, that is, you can define new implementations of this method in the derived class. The following modifiers are used to control how to rewrite properties and methods:
OVERRIDABLE - Allows the properties or methods in a class to be rewritten in the derived class. Overrides - Rewrive the Overridable property or method defined in the base class. NOTOVERRIDABLE - Prevents an attribute or method from being rewritten in the inheritance class. By default, the public method is NOTOVERRIDABLE. Mustoverride - Requires the rendering of the property or method. When using the Mustoverride keyword, the method definition consists only of the SUB, FUNCTION, or the Property statement. Other statements are not allowed, especially if there is an end sub or end function statement. The Mustoverride method must be declared in the Mustinherit class. For more information on rewriting methods, see Rewriting Properties and Methods
MyBase Keyword When rewriting the method in the derived class, you can use the method in which the MYBASE keyword calls the base class. For example, suppose you are designing a derived class that rewriting methods from the base class inheritance. The way to rewrite the method in the base class, and modify the return value, as shown in the following code segment: Class DeriveDClass Inherits Baseclass Public Overrides Function Calculateshipping (Byval Dist As Double, _ Byval Rate As Double) AS Double ' Call The Method In The Base Class and Modify The Return Value. Return mybase.calculateshipping (dist, rate) * 2 End funnd Class The following list Description Limitations using MyBase:
MyBase reference direct base class and its inheritance member. It cannot be used to access Private members in the class. Mybase is a keyword, not an actual object. MyBase cannot be assigned to the variable, and cannot be passed to the process, or it cannot be used in the IS comparison. MyBase defined methods do not need to be defined in the direct base class, which can be defined in indirectly inherited base classes. In order to correctly compile myBase defined references, some base classes must contain methods that match the parameter names and types that appear in the call. You cannot use MyBase to call the Mustoverride base class. MyBase cannot be used to limit itself. Therefore, the following code is illegal: mybase.mybase.btnok_click () 'syntax error.mybase cannot be used in the module. If the base class is concentrated in different assemblies, you cannot use MyBase to access the base class member marked as Friend. Myclass Keyword MyClass keyword enables you to call the Overridable method implemented in the class and make sure to call the implementation of this method in this class, not the method of rewriting in the derived class.
Myclass is a keyword, not an actual object. MyClass cannot assign a variable, and cannot be passed to the process, and it is also not available in the IS comparison. Myclass references contain classes and their inheritance members. MyClass can be used as a modifier of Shared members. MyClass cannot be used in standard modules. MyClass can be used to define such a method, which is defined in the base class but does not provide the implementation of the method in this class. The meaning of this reference is the same as mybase.method. Most of the object-oriented programming systems based on inheritance provides polymorphisms. The inherited polymorphism involves defining methods in the base class and rewriting them in the derived class.
For example, you can define a class BaseTax that provides a reference function for calculating a sales tax of a state / province. Classes derived from Basetax, such as countytax or citytax, if appropriate, can implement a method such as CalculaTax.
Polymorphism comes from this fact: You can call the CalculaTax method belonging to any class of any class derived from BaseTax, without having to know which class belongs to this object.
The TestPoly process demonstration in the example below is based on inheritance:
Const StateRate As Double = 0.053 '% 5.3 State taxConst CityRate As Double = 0.028'% 2.8 City taxPublic Class BaseTax Overridable Function CalculateTax (ByVal Amount As Double) As Double Return Amount * StateRate 'Calculate state tax. End FunctionEnd ClassPublic Class CityTax' This method calls a method in the base class' and modifies the returned value. Inherits BaseTax Private BaseAmount As Double Overrides Function calculateTax (ByVal Amount As Double) As Double 'Some cities apply a tax to the total cost of purchases,' including other taxes. BaseAmount = mybase.calculatetax (amount) Return CityRate * (BaseAmount Amount) BaseAmount End Functionend Class
Sub testpoly () DIM ITEM1 AS New BaseTax () Dim Item2 As New CityTax () ShowTax (Item1, 22.74) '$ 22.74 Normal Purchase. ShowTax (Item2, 22.74)' $ 22.74 City Purchase. End Sub
Sub ShowTax (ByVal Item As BaseTax, ByVal SaleAmount As Double) 'Item is declared as BaseTax, but you can' pass an item of type CityTax instead. Dim TaxAmount As Double TaxAmount = Item.CalculateTax (SaleAmount) MsgBox ( "The tax is : "& Format," C ")) End Sub In this example, the ShowTax process accepts the parameters named Item named Item, but can also pass any class derived from the shape, such as CityTax. The advantage of this design is to add new classes derived from the BaseTax class without changing the client code during the showTax.