CLASSES

A class packages data and related behavior. For example, a WorkOrder class might store data describing a customer’s work order in its properties. It could contain methods (subroutines and functions) for manipulating the work order. It might provide methods for scheduling the work, modifying the order’s requirements, and setting the order’s priority.

Here is the syntax for declaring a class:

[attribute_list] [Partial] [accessibility] [Shadows] [inheritance] _
Class name[(Of type_list)]
    [Inherits parent_class]
    [Implements interface]
    statements
End Class

The only things that all class declarations must include are the Class clause (including the class’s name) and the End Class statement. Everything else is optional. The following code describes a valid (albeit not very interesting) class:

Class EmptyClass
End Class

The following sections describe the pieces of the general declaration in detail.

Attribute_list

The optional attribute_list is a comma-separated list of attributes that apply to the class. An attribute further refines the definition of a class to give more information to the compiler and the runtime system.


AVOID COMMA DRAMA
Instead of using commas to separate multiple attributes inside one set of brackets, you can place each attribute inside its own brackets. For example, the following code defines two classes, each having two attributes: Serializable and Obsolete.
<Serializable(), Obsolete("No longer supported. Use Sku instead")>
Public Class SkuNumber
    ...
End Class
 
<Serializable()>
<Obsolete("No longer supported. Use ProductType instead")>
Public Class Product
    ...
End Class
Which style you should use is a matter of personal preference, although it’s slightly easier to insert or remove attributes with the second style because you can add or remove whole lines at a time without messing up the commas.

Attributes are rather specialized. They address issues that arise when you perform very specific programming tasks. For example, if your application must use drag-and-drop support to copy instances of the class from one application to another, you must mark the class with the Serializable attribute.

Some attributes are particular to specific kinds of classes. For example, the DefaultEvent attribute gives the Windows Form Designer extra information about component classes. If you double-click a component on a form, the code designer opens to the component’s default event.

Because attributes are so specialized, they are not described in more detail here. For more information, see the sections in the online help that are related to the tasks you need to perform.

For more information on attributes, see Microsoft’s “Attributes in Visual Basic” web page at http://msdn.microsoft.com/39967861.aspx. For a list of attributes that you can use, go to Microsoft’s “Attribute Class” web page at http://msdn.microsoft.com/system.attribute.aspx and look at the “Inheritance Hierarchy” section.

Partial

The Partial keyword tells Visual Basic that the current declaration defines only part of the class. The following code shows the Employee class broken into two pieces:

Partial Public Class Employee
    Public FirstName As String
    Public LastName As String
    ...
End Class
 
... other code, possibly unrelated to the Employee class ...
 
Partial Public Class Employee
    Public Email As String
    ...
End Class

The program could contain any number of other pieces of the Employee class, possibly in different code modules. At compile time, Visual Basic finds these pieces and combines them to define the class.

One of the primary benefits of classes is that they hold the code and data associated with the class together in a nice package. Scattering the pieces of a class in this way makes the package less self-contained and may lead to confusion. To prevent confusion, you should avoid splitting a class unless you have a good reason to (for example, to allow different developers to work on different pieces of the class at the same time or if one piece must have Option Strict turned off).

At least one of the pieces of the class must be declared with the Partial keyword, but in the other pieces it is optional. Explicitly providing the keyword in all of the class’s partial definitions emphasizes the fact that the class is broken into pieces and may reduce confusion.

Accessibility

A class’s accessibility clause takes one of the following values: Public, Protected, Friend, Protected Friend, or Private.

Public indicates that the class should be available to all code inside or outside of the class’s module. This enables the most access to the class. Any code can create and manipulate instances of the class.

You can use the Protected keyword only if the class you are declaring is contained inside another class. For example, the following code defines an Employee class that contains a protected EmployeeAddress class:

Public Class Employee
    Public FirstName As String
    Public LastName As String
    Protected Address As EmployeeAddress
 
    Protected Class EmployeeAddress
        Public Street As String
        Public City As String
        Public State As String
        Public Zip As String
    End Class
 
    ... other code ...
End Class

Because the EmployeeAddress class is declared with the Protected keyword, it is visible only within the enclosing Employee class and any derived classes. For example, if the Manager class inherits from the Employee class, code within the Manager class can access the Address variable.

The Friend keyword indicates that the class should be available to all code inside or outside of the class’s module within the same project. The difference between this and Public is that Public allows code outside of the project to access the class. This is generally only an issue for code libraries (.dll files) and control libraries. For example, suppose that you build a code library containing dozens of routines and then you write a program that uses the library. If the library declares a class with the Public keyword, the code in the library and the code in the main program can use the class. If the library declares a class with the Friend keyword, only the code in the library can access the class, not the code in the main program.

Protected Friend is the union of the Protected and Friend keywords. A class declared Protected Friend is accessible only to code within the enclosing class or a derived class and only within the same project.

A class declared Private is accessible only to code in the enclosing module, class, or structure. If the EmployeeAddress class were declared Private, only code within the Employee class could use that class.

If you do not specify an accessibility level, it defaults to Friend.

Shadows

The Shadows keyword indicates that the class hides the definition of some other entity in an ancestor class.

The following code shows an Employee class that declares a public class OfficeInfo and defines an instance of that class named Office. The derived class Manager inherits from Employee. It declares a new version of the OfficeInfo class with the Shadows keyword. It defines an instance of this class named ManagerOffice.

Public Class Employee
    Public Class OfficeInfo
        Public OfficeNumber As String
        Public Extension As String
    End Class
 
    Public FirstName As String
    Public LastName As String
    Public Office As New OfficeInfo
End Class
 
Public Class Manager
    Inherits Employee
 
    Public Shadows Class OfficeInfo
        Public OfficeNumber As String
        Public Extension As String
        Public SecretaryOfficeNumber As String
        Public SecretaryExtension As String
    End Class
 
    Public ManagerOffice As New OfficeInfo
End Class

The following code uses the Employee and Manager classes. It creates instances of the two classes and sets their Office.Extension properties. Both of those values are part of the Employee class’s version of the OfficeInfo class. Next, the code sets the Manager object’s ManagerOffice.SecretaryExtension value.

Dim emp As New Employee
Dim mgr As New Manager
emp.Office.Extension = "1111"
mgr.Office.Extension = "2222"
mgr.ManagerOffice.SecretaryExtension = "3333"

Note that the Manager class contains two different objects of type OfficeInfo. Its Office property is the Employee class’s flavor of OfficeInfo class. Its ManagerOffice value is the Manager class’s version of OfficeInfo.

The presence of these different classes with the same name can be confusing. Usually, you are better off not using the Shadows keyword in the declarations and giving the classes different names. In this case, you could call the Manager class’s included class ManagerOfficeInfo.

Inheritance

A class’s inheritance clause can take the value MustInherit or NotInheritable.

MustInherit prohibits the program from creating instances of the class. The program should create an instance of a derived class instead. This kind of class is sometimes called an abstract class.

By using MustInherit, you can make a parent class that defines some of the behavior that should be implemented by derived classes without implementing the functionality itself. The parent class is not intended to be used itself, just to help define the derived classes.

The NotInheritable keyword does the opposite of the MustInherit keyword. MustInherit says that a class must be inherited to be instantiated. NotInheritable says no class can inherit from this one.

You can use NotInheritable to stop other developers from making new versions of the classes you have built. This isn’t really necessary if you design a well-defined object model before you start programming and if everyone obeys it. NotInheritable can prevent unnecessary proliferation of classes if developers don’t pay attention, however. For example, declaring the Car class NotInheritable would prevent overeager developers from deriving FrontWheelDriveCar, RedCar, and Subaru classes from the Car class.


EXTENSION TENSION
Extension methods allow developers to add new subroutines and functions to a class even if it is marked NotInheritable. This can ruin the class’s focus of purpose, making it harder to understand and use safely. It also violates the intent of the NotInheritable keyword so you should avoid it if possible. For more information, see the section “Extension Methods” in Chapter 22, “OOP Concepts.”

Of type_list

The Of type_list clause makes the class generic. It allows the program to create instances of the class that work with different data types. For example, the following code defines a generic Tree class. The class includes a public variable named RootObject that has the data type given in the class’s Of data_type clause.

Public Class Tree(Of data_type)
    Public RootObject As data_type
    ...
End Class

When you read this declaration, you should think “Tree of something,” where something is defined later when you make an instance of the class.

The following code fragment declares and instantiates the variable my_tree to be a “Tree of Employee.” It then sets its RootObject variable to a new Employee object.

Dim my_tree As New Tree(Of Employee)
my_tree.RootObject = New Employee
...

Chapter 26, “Generics,” discusses generic classes further.

Inherits parent_class

The Inherits statement indicates that the class (the child class) is derived from another class (the parent class). The child class automatically inherits the parent’s properties, methods, and events.

The following code defines an Employee class that contains LastName, FirstName, OfficeNumber, and Phone variables. It then derives the Manager class from the Employee class. The Manager class adds new SecretaryOfficeNumber and SecretaryPhone variables. These are available to instances of the Manager class but not to the Employee class.

Public Class Employee
    Public FirstName As String
    Public LastName As String
    Public OfficeNumber As String
    Public Phone As String
End Class
 
Public Class Manager
    Inherits Employee
 
    Public SecretaryOfficeNumber As String
    Public SecretaryPhone As String
End Class

If a class inherits from another class, the Inherits statement must be the first statement after the Class statement that is not blank or a comment. Also note that a class can inherit from at most one parent class, so a class definition can include at most one Inherits statement.

For more information on inheritance, see the section “Inheritance” in Chapter 22.

Implements interface

The Implements keyword indicates that a class will implement an interface. An interface defines behaviors that the implementing class must provide, but it does not provide any implementation for the behaviors.

For example, the following code defines the IDomicile interface. (By convention, the names of interfaces should begin with the capital letter I.)

Public Interface IDomicile
    Property SquareFeet As Integer
    ReadOnly Property NeedsFireSystem As Boolean
    Sub Clean()
End Interface

The House class shown in the following code implements the IDomicile interface. When you type the Implements statement and press Enter, Visual Basic automatically generates empty routines to provide the features defined by the interface.

Public Class House
    Implements IDomicile
 
    Public Sub Clean() Implements IDomicile.Clean
 
    End Sub
 
    Public ReadOnly Property NeedsFireSystem As Boolean _
     Implements IDomicile.NeedsFireSystem
        Get
 
        End Get
    End Property
 
    Public Property SquareFeet As Integer Implements IDomicile.SquareFeet
End Class

If a class declaration uses any Implements statements, they must come after any Inherits statement and before any other statements (other than blank lines and comments).

For more information on interfaces and how you can use them to mimic inheritance, see the section “Interface Inheritance” in Chapter 22.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.186.244