Defining Private Class Members
All functionality and data truly encapsulated by a class and not available to any outside user or derived class are defined as private. When you're designing "black box" classes, all supporting methods, classes, and data aren't needed by any user except the class itself.
The class definition in Listing 3.3 shows a class that has private member data and methods defined to implement the public interface.
Listing 3.3 CircleButton.vb: CircleButton Class Modified to Encapsulate Functionality
Class CircleButton 'Public draw functions Public Sub DrawRedButton(ByRef DrawOn As Windows.Forms.Form) Draw(DrawOn, Drawing.Color.Red) End Sub Public Sub DrawBlackButton(ByRef DrawOn As Windows.Forms.Form) Draw(DrawOn, Drawing.Color.Black) End Sub 'Private subroutine to draw the circle button in the specified color Private Sub Draw(ByRef DrawOn As Windows.Forms.Form, _ ByVal Color As Drawing.Color) ... End Sub End Class
Listing 3.3 shows a simple instance in which a class has a public interface that calls a private method. In this case, the Color parameter is added to the Draw() method, and two new public methods, DrawRedButton() and DrawBlackButton(), are defined to draw red and black buttons. The object's user doesn't have to know or care what it takes to draw the red or black buttonand doesn't need to. The details are hidden from the public interface, providing object users a more intuitive interface. In more complex classes, providing simple public interfaces that encapsulate more complex interfaces is one feature that makes object-oriented programming quicker and self-documenting.
Sometimes it's necessary for a class to define other classes used only within the class implementation. By encapsulating other class definitions, a class defines its own private objects for implementation of the overall functionality. Without encapsulation, these class definitions are available for other classes to use, which sometimes isn't desirable. The following code shows how a class defines its own classes:
Public Class MyTestClass ' Can be used as MyTestClass.PublicInnerClass by anyone Public Class PublicInnerClass '... End Class ' Can only be used by MyTestClass or derivatives Protected Class ProtectedInnerClass '... End Class ' Can only be used by MyTestClass Private Class PrivateInnerClass '... End Class End Class
As you can see in the code segment, a class also can provide other class definitions available for use outside MyTestClass. For example, an object may have a closely related object class that it uses for keeping internal information. However, if that information is made available as part of the public interface, the internal class must also be publicly available. The internal public class, PublicInnerClass, is referenced by using the following statement:
Attempts to reference nonpublic classes defined within MyTestClass won't compile because they aren't available for public use.