VB.net learning notes (13) abstract class and multi-interface

Source: Internet
Author: User

When I handed in my homework to an art teacher, one student handed in only one blank sheet of paper.
The teacher asked: "What about painting ?"
Student A: "here ?" He pointed to the White Paper and said.
Teacher: "What did you draw ?"
Student: "cattle graze ."
Teacher: "What about grass ?"
Student: "The ox has eaten up ."
INSTRUCTOR: "What about Ox ?"
Student: "What are the cows standing there ?"

1. abstract base class

Just as a good father can struggle for less than one person, the parent class itself is very useful. It can be instantiated or not instantiated. It is of great benefit to make it look like it.

1. mustinheit

The base class can be instantiated, but it can also be not instantiated (or the object of this class cannot be created). In this case, only subclass and subclass objects can be created.

You can use mustinherit to specify that the base class cannot create objects.

Note: This does not mean that you cannot declare variables of the base class (in the following example, person) type, but you cannot use new peron to create objects.

At the same time, we can continue to use the sharing method (because it only belongs to the class and does not belong to the object)

2. mustoveride

Specifies a method (sub, funciton, and property) that can only be overwritten by a subclass. This method only has a method header and has no specific implementation code. Therefore, you cannot create an object.

Therefore, when a class contains mustoveride, the class must be declared by mustinherit. That is:

Mustoverride can only be used in attribute and process declaration statements. The mustoverride attribute or process must be a member of the class, and the class must be labeled

As mustinherit.

Public mustinherit class person can only be inherited from private mname as string private mbirthdate as date private mid as string public event namechanged (byval newname as string) public event datachanged (byval field as string, byval newvalue as object) Public mustoverride function lifeexpectancy () as integer 'no implementation code, only the quilt class override '...... end Class

The above Declaration states that the mustoveride function lifeexpectancy only has a method header and no implementation code. Such methods are also called "Abstract METHODS" or "pure virtual functions"

Any subclass that inherits this class must override these abstract methods. Otherwise, a syntax error will occur and the subclass will not be compiled.

Therefore, add the following in the subclass:

'======= Override the pure virtual function of the base class in the sub-class employee =================== public overrides function lifeexpectancy () as integer return 90 end Function

3. abstract base class

This class is called an abstract base class when both mustinherit and mustoverride appear. Or: Classes containing abstract methods are called abstract base classes.

Abstract base classes are very useful. In the early stage, only the abstract base classes can be shelved. each subclass can rewrite its own method based on its own situation.

Note that at this time, the subclass must have the implementation code of the abstract method. Otherwise, an error occurs.

Public mustinherit class abstractbaseclass public mustoverride sub dosomething () Public mustoverride sub doothersomething () End Class 'interface public interface begin sub dosomething () sub doothersomething () End Interface

In some aspects, the abstract base class is similar to the interface concept. The above interface iabstractbaseclass must have two methods in the class to implement this interface.

Otherwise, an error occurs.

4. Prohibit inheritance

The above is the object that can only be inherited.

The following is "forbidden inheritance", which is described by notineritable. inheritance is not allowed until now!

Public notinheritable class officeemployee 'specifies that the base is no longer a base class (that is, no further derivation)

Classes that cannot be inherited are sometimes called "sealed" classes.

Ii. Multiple Interfaces

Interface, like a diplomat, can communicate with the outside world.

In VB.net, an object can have one or more interfaces. All objects have a primary interface or a local interface. interfaces are declared by public methods, attributes, events, and fields.

In addition to local interfaces, implements can be used to implement secondary interfaces for objects.

1. object interface

Class can be used as a local interface except for private declarations. Example:

'Method as interface public sub amethod () end sub' attribute as interface public property aproperty () as string end properties' event as interface public event aevent () 'variable as interface public ainteger as integer

Note: There is no implementation code above, because the interface only lies in the declaration of the shelf, and the implementation code in it is not part of the interface. This is an important difference!

The difference between interfaces and implementation code is the core content of object-oriented programming.

Use local interfaces

Once the local interface is declared, these interfaces can be used in the object to communicate with the outside world. The pulbic method in the following class, and its object can be directly connected with the outside world.

'============ Local interface of the class ======== public class theclass public sub dosomething ()'..... end sub public sub doothersomething ()'....... end subend class '========= use these two interfaces in the main program ======== dim myobject as new theclass myobject. dosomething () myobject. doothersomething ()

2. Auxiliary Interfaces

In terms of design, only similar objects have the same local interface, which imposes great restrictions.

If a set of different objects have different local interfaces, the processing will be troublesome.

For example, for products, customers, and invoices, there is no natural inheritance relationship. However, we need to print these three pieces of information,

Another concept "Auxiliary interface" is created, that is, the interface that is usually used, through which all three can be printed.

The interface is the same level of concept as the class and the modul. It does not implement code like an abstract method, and the implementation code is using interfaces.

. In this way, you do not have to worry about the same type of object.

(1) define interfaces

An interface is used to define an interface. By adding a module, the interface code is added outside the module:

Public interface iprintableobject: The function label (byval index as integer) as string 'has the same scope as class and module. Therefore, no public interface exists, function value (byval index as integer) as string readonly property count () as integerend interfacemodule interfacesend Module

The interface definition is included in the interface and End Interface statements.

After the interface statement, you can add the inherits statements that list one or more inherited interfaces. That is, the interface can be inherited.

In the declaration, the inherits statement must appear before all other statements except the annotation.

The remaining statements in the interface definition should include the event, sub, function, property, interface, class, structure, and enum statements.

The interface cannot contain any implementation code or statements associated with the implementation code, such as end sub or end property.

In a namespace, the interface statement is friend by default, but it can also be explicitly declared as public or friend.

The interfaces defined in classes, modules, interfaces, and structures are public by default, but can also be explicitly declared as public, friend, protected, or private.

The Shadows keyword can be applied to all interface members. The overloads keyword can be applied to sub, function, and property statements declared in the interface definition.

In addition, the property statement can have the default, readonly, or writeonly modifier. Do not use any other modifiers: Public, private,

Friend, protected, shared, overrides, mustoverride, or overridable.

An interface is a data type, similar to a class or structure (struction ). This is because variables of this type can be defined as follows:

    Private printable As IPrintableObject

But none of the above implements the code, and the implementation code is implemented in the class. Therefore, the new interface cannot be used directly.

(2) Use Interfaces

Users only need to know the interface and can use different objects without having to know the internal details of objects.

Add method in the form:

Public sub printobject (OBJ as iprintableobject) 'add the routine dim index as integer for Index = 0 to OBJ in the form. count debug. write (obj. label (INDEX) & ":") debug. writeline (obj. value (INDEX) Next end sub

Then add the button in the form and add the Code:

Private Sub ButtonPrint_Click(sender As Object,e As EventArgs) Handles ButtonPrint.Click    Dim obj As New Employee()    obj.EmployeeNumber = 123    obj.BirthDate = #1/1/1980#    obj.HireDate = #1/1/1996#    PrintObject(obj)End Sub

When you click "run", an error is prompted because the interface is only a method header or an event header and there is no specific implementation code. Therefore, you must add the implementation code to the class.

(3) Implementation Interface

Any class (except the abstract base class) can use implements to implement interfaces.

Because the interface must be passed through the class object, the interface is finally said. Abstract base classes cannot generate objects, so abstract base classes cannot have interfaces.

After you add implements, press enter to automatically add the methods or events of the interface to the class. We only need to add the implementation code to the class.

The names of methods and properties implemented in the class are not important. It is important that the data type and return value of the parameter must match the type defined by the interface.

The implementation code is as follows:

'==================== Interface implementation in the employee class (connected to the external interface type) ========= implements iprintableobject here press enter to automatically add the iprintableobject member to implement the details 'private mlabels (), the field to be used or prepared for the interface () as string = {"ID", "Age", "hiredate"} private mbirthdate as date private msalary as double public readonly property count as integer implements iprintableobject. count get return ubound (mlabels) end get end property private function label (index as integer) as string implements iprintableobject. label return mlabels (INDEX) end function public function value (index as integer) as string implements iprintableobject. value select case index case 0 return CSTR (employeenumber) Case 1 return CSTR (AGE) case else return format (hiredate, "short date") end select end Function

Note: You can see that implements iprintableobject. label is followed by the implementation method. This is similar to handles. It can also use commas

Multiple methods of an interface are connected to one method, or the methods of multiple interfaces are connected to one method.

(Actually, it is to associate the function address with the outside world. Using this address will naturally call methods in different objects)

Take a look at the entire interface:

(4) Reuse common implementation code

Auxiliary interface, there can be several, a few can be the same method, this method becomes a common method.

The following two interfaces are related to the same method value (class employe)

'========= Interface 1, value ======================== public interface iprintableobject function label (byval index as integer) as string function value (byval index as integer) as string readonly property count () as integerend interface '====== interface 2, getvalue ==================== public interface ivales function getvalue (byval index as integer) as stringend interface '====== two interfaces in employee, are associated with the value function at the same time (the function signature is the same as the above parameter) ============ implements iprintableobject implements ivales public function value (index as integer) as string implements iprintableobject. value, ivales. getvalue select case index case 0 return CSTR (employeenumber) Case 1 return CSTR (AGE) case else return format (hiredate, "short date") end select end Function

As you can see, it is represented by a comma, and both interfaces use the value method.

(5) merging interfaces and inheritance

Secondary interfaces can be merged and inherited at the same time.

When inheriting from a class that implements an interface, the new subclass automatically obtains the implementation code of the interface and the base class.

If the base class method can be rewritten, The subclass can override these methods.

You can not only rewrite the implementation code of the base class main interface, but also the implementation code of the interface.

Public Overridable Function Value(ByVal index As Integer) As String  Implements IPrintableObject.Value, IValues.GetValue

The above indicates that this interface can be rewritten.

The complete definition is as follows:

    Public Overridable Function Value(index As Integer) As String Implements IPrintableObject.Value, IVales.GetValue        Select Case index            Case 0                Return CStr(EmployeeNumber)            Case 1                Return CStr(Age)            Case Else                Return Format(HireDate, "Short date")        End Select    End Function

Note: because the above is public, it is also valid in the main interface (Local interface.

It is also a part of the two interfaces, which means it can be accessed in three ways.

Three access methods:

        Dim emp As New Employee("Andy")        Dim printable As IPrintableObject = emp        Dim values As IVales = emp        Debug.WriteLine(emp.Value(0))        Debug.WriteLine(printable.Value(0))        Debug.WriteLine(values.GetValue(0))

First: Primary Interface (Local interface)

Type 2: iprintableobject interface access

Third: ivalues interface access

All these three interfaces are combined in the value method.

 

To declare the implementation of the interface method, you can use any valid features (including overloads, overrides, overridable, public, private, protected, friend, protected friend, mustoverride, default, and static) on the instance method declaration ).

The shared feature is invalid because it defines classes rather than instance methods.

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.