Members and Scope
Most classes, with few exceptions, have member data defined. The member data stores the state information of an object when a class is instantiated, or an instance is created. Some classes provide functionality only and have no state information; however, those classes aren't as common.
In the SimpleMsg class from Listing 1, the only member is strMessage, which stores the message of the object. The SmartMsg class in Listing 1 doesn't have any state information and therefore no members. It only enhances the SimpleMsg class by providing more functionality.
You can think of objects as black boxes in which only the implementer knows how the data is stored and how functionality is implemented. An object's user doesn't care about these details, and in many cases, the object's implementer doesn't want the user to know. A class can define the scope of member data and functionality that determines the type of access users have to an object's member data and functionality. Scope of member data and functionality can be private, protected, or public.
When you define a class's member data and/or methods that won't be directly accessed by other classes or classes that inherit from this class, you declare them as private. Declaring them as private means the data and/or methods are accessible only from within the class.
Classes define member data as private when it's imperative that only that class modifies the data. Even a class that inherits from a class with private members can't modify the data. You might declare it as private when member data requires special processing if it's modified or if it's only for use internally and doesn't have any value to another class.
In general, it's a good practice to declare member data as private and provide accessor functions to retrieve or change its value. For example, the SimpleMsg class in Listing 1 declares the strMessage member as Private. An accessor, MsgText(), is provided to retrieve and set the value.
Methods within a class can also be declared as private when they should never be called outside the class. If the class has internal functions or subroutines used as part of a class's functionality and that have no valid use outside the class, they should be declared as private also.
A good time to declare methods as private would be when a subroutine or function is declared in a class and used as part of an overall class-specific process. You don't want another class calling that function directly because it would be out of the context within which it was designed to work. When you declare it with Private, no other classes can call the function, which makes the class less vulnerable to bugs caused from misuse.
When designing a class, you should declare as much as possible of the class's data and methods as private while maintaining the usefulness of the class. Doing so makes your class less vulnerable to misuse by other classes and keeps the class data manipulation under the class's control, where it's less likely to be manipulated incorrectly.
You also can define methods to allow access to all class data so that there is no need for any class data to be declared as anything other than private.
What if a class needs to have data and/or methods that are visible only within the class but also by any classes that inherit it? The protected member data and methods provide this level of access. Protected is similar to private in that the user can't directly access the member data or methods, but other classes that inherit a class with protected members and methods can access them as if they were their own.
The most common use of the Protected declaration is on methods that are accessible only from derivative classes, as shown in the following:
Protected Sub btnCancel_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnCancel.Click Close() End Sub
Declaring the btnCancel_Click() method as Protected keeps other objects from using it but allows a derived class object to use it as necessary. Event handlers are commonly declared this way because they shouldn't be called from outside the object.
Occasionally, member data is marked as protected if a derivative class can safely modify it directly. Again, making member data protected isn't recommended unless it's safe to be modified without any special process.
The last of the three class scope declarations is Public. As its name implies, it allows any user or other class to access whatever member data or method is declared public. Generally, classes are designed so that only methods are declared public and member data is private and sometimes declared as protected. Making class member data public is not a good practice because this data can be accessed and modified by any other class. Making data accessible defeats one of the purposes of object-oriented programming: keeping data and functionality contained within objects.
An example of a commonly defined public method within a class is New(). All classes in Visual Basic .NET that have initialization work when the class is instantiated declare a New() method, which must be declared Public. When a class is instantiated with the New operator, an object of the class type is allocated, and the New() method is called if one is defined.
When you design a class, you need to decide what type of public interface the class should have and declare the appropriate subroutines and functions as Public. Users of the class can directly call only those methods that are declared public. Thus, the class designer can control the use of the class and which features are exposed for use by public users.
Sometimes all objects of a given class need to share a common value. For example, if you want to track the number of instances of a particular class that are in use, you could add a counter to a class that's incremented every time a new object is created and decremented whenever an object is deleted.
You can declare a global variable to track data; however, the value is then visible to the entire application and is no longer directly tied to your class. Object-oriented programming techniques require declaring such variables as static members within the class definition. Visual Basic .NET facilitates declaring static members by declaring them with the Shared specification, as follows:
Class MyCountClass Private Shared InstanceCount As Integer = 0 Public Sub New() InstanceCount += 1 'Other initialization code End Sub Public Sub Dispose() InstanceCount -= 1 'Other cleanup code End Sub End Class
Although the Static keyword exists in the VB language, Microsoft chose to use the Shared keyword in Visual Basic .NET to indicate that a class member or method is static.
Unlike typical member variables in which each object of a class type has its own copy of a member variable, static or shared member variables are shared among all instances of a class. So, in the preceding example, the InstanceCount variable can keep track of the number of instances of MyCountClass currently in use.
Also, any shared member or method within a class can be accessed without an actual instance of the class. You can do this because any shared member is actually allocated when the application starts or when the class is first used because the member is valid for the entire life of the application. For example, if the InstanceCount member was declared Public, you could access or assign a value to InstanceCount at any time within the application with the following:MyCountClass.InstanceCount = 0
Final and Abstract
You can create classes that can never exist as an object without being inherited by another class. You also can create a class that can never be inherited by another class. Both concepts are related by the extremes they represent.
As you've learned, you can create a class and then derive another class from the first class by inheriting from it. When you do so, your new class inherits the functionality from the first class and builds on its functionality. Now, suppose that you've created a class that you must derive from and implement additional functionality before it's useful. Such classes are often low-level base classes that don't implement specific functionality but rather contain the building blocks for more complex classes. To enforce a user of such a class to build a new class, Visual Basic .NET provides a MustInherit specifier for the class definition.
The code in Listing 2 shows a class, GraphicObject, that is declared as MustInherit, and has a Draw() subroutine defined as MustOverride. When you declare a method as MustOverride, the class becomes abstract because functionality is left undefined.
Listing 2GraphicObject, Circle, and Square Class Definitions
MustInherit Class GraphicObject Protected Dimensions As System.Drawing.Rectangle Public Sub New(ByRef Rect As System.Drawing.Rectangle) Dimensions = Rect Draw() End Sub Public MustOverride Sub Draw() End Class NotInheritable Class Circle Inherits GraphicObject Public Sub New(ByRef Rect As System.Drawing.Rectangle) MyBase.New(Rect) End Sub Public Overrides Sub Draw() 'Draw a Circle End Sub End Class NotInheritable Class Square Inherits GraphicObject Public Sub New(ByRef Rect As System.Drawing.Rectangle) MyBase.New(Rect) End Sub Public Overrides Sub Draw() 'Draw a Square End Sub End Class
An application can't instantiate a new GraphicObject class directly because it has the MustInherit declaration; therefore, new classes are created. The first class, Circle, will draw a circle object, whereas the second class, Square, will draw a square.
The only functionality necessary for the Circle and Square classes to implement is the actual drawing code; all other functionality resides in the GraphicObject class. To enforce providing the Draw() functionality, you declare a Draw() subroutine in the GraphicObject class with the MustOverride specifier. Now any classes that inherit from GraphicObject must override the Draw() subroutine to provide the appropriate functionality.
Any time the GraphicObject class uses the Draw() subroutine, as it does in the New() subroutine, the Draw() subroutine in the derived class is actually called to draw the appropriate shape.
In this example, the Circle and Square classes are declared as NotInheritable, which means that they are final classes and can't ever be inherited to make a new class. This capability can be useful when a class is complete and the class's builder doesn't want any further enhancements made through inheritance.
Say that the design calls for the class to still be inheritable, but a particular method should never be overridden, which would prevent proper function. You can specify NotOverridable in the same manner as MustOverride was used in Listing 2 to protect a function from being overridden. In a class already marked as NotInheritable, you don't need to specify NotOverridable because no class can inherit from such a class in order to override a method.