Home > Articles > Programming > Windows Programming

Learning to Speak OOP

This chapter is from the book

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
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.

Static Members

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 2—GraphicObject, 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

  End Sub

  Public MustOverride Sub Draw()
End Class

NotInheritable Class Circle
    Inherits GraphicObject

  Public Sub New(ByRef Rect As System.Drawing.Rectangle)
  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)
  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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020