Home > Articles

This chapter is from the book

Introducing Classes and Objects

Object-oriented programming (OOP) is a topic that is central to Visual Basic, and we're going to take it step by step, getting an introduction to classes and objects today and continuing our OOP work throughout the book.

Yesterday, we worked with simple variables, like this integer variable:

Dim intItem1 As Integer

Here, intItem1 is the variable and Integer is the variable's type. In the same way, you can declare objects, using a class as the object's type:

Dim TheObject As TheClass

Here, TheObject is an object of TheClass class. In this way, you can think of a class as an object's type. What's different about a class from a simple type like an Integer? The difference is that classes and objects can contain members. As we've already seen, one type of member is a property, which holds data, and you access an object's properties with a dot followed by the property name like this:

TheObject.TheProperty = "Hello!"

Classes and objects can also contain built-in procedures, called methods. A method can either be a Sub procedure or a function, and you call it as you would any other procedure, except that you need to preface the method name with the class or object name and a dot like this, where TheMethod returns a message as a text string:

Dim Message As String = TheObject.TheMethod()

In practice, you usually use the properties and methods of objects only. Classes can support properties and methods directly, without needing to create an object, but you have to make special provisions in the class, as we'll see in Day 9. Those members of a class that you can use with the class directly without needing to create an object first are called class members; for example, if TheMethod was a class method, you could use it with the class name, no object needed:

Dim Message As String = TheClass.TheMethod()

Encapsulation

So now you know the relation of an object to a class; it's much like the relation of a cookie to a cookie cutter or a variable to the variable's type. What's good about this is that you can pack a great deal into an object, and the programmer no longer has to deal with a great many separate properties and procedures; they're all wrapped up in an easily-thought-of object. All the internal details are out of sight, out of mind. In fact, OOP was first created to help you deal with code as programs grew longer and longer by wrapping up that code into objects to simplify things, a process called encapsulation.

For example, think of a car. Under the hood, dozens of things are going on: The fuel pump is pumping, the pistons are firing, the distributor and timing belt are timing the power sent to the pistons, oil is circulating, voltage is being regulated, and so on. If you had to attend to all those operations yourself, there's no way you could drive at the same time. But the car takes care of those operations for you, and you don't have to think about them (unless they go wrong and have to be "debugged," of course...). Everything is wrapped up into an easily handled concept—a car. You get in, you drive.

You don't have to say that you're going to drive off and regulate oil pressure, pump water, feed gas to the engine, and time the spark plugs. You just drive off. The car presents you with a well-defined "interface" where the implementation details are hidden; you just have to use the pedals, steering wheel, and gear shift, if there is one, to drive.

That's similar to the objects you'll see in Visual Basic. For example, the user-interface elements we'll see tomorrow—text boxes, buttons, even Windows forms—are all objects. They all have properties and methods that you can use. Behind the scenes, there's a lot going on, even in a text box object, which has to draw itself when required, store data, format that data, respond to keystrokes, and so on. But you don't have to worry about any of that; you just add a text box to your program and it takes care of itself. You can interact with it by using a well-defined programming interface made up of properties like the Text property (as in TextBox1.Text = "Hello!"), which holds the text in a text box, and methods like the Clear method, which erases all text in the text box (and which you call like this: TextBox1.Clear()).

An Example in Code

The Windows forms that we'll be creating in the next five days are all classes, created with the Class statement, as we'll see tomorrow. For that reason, let's look at an example that creates a class and an object in code. This example will be much simpler than the Visual Basic TextBox class, but it's similar in many ways: Both the TextBox class and our new class are created with a Class statement, and both will support properties and methods. This example will start giving us the edge we need when dealing with OOP.

Creating a Class

How do you actually create a class? You use the Class statement:

[ <attrlist> ] [ Public | Private | Protected | Friend | Protected Friend ]
[ Shadows ] [ MustInherit | NotInheritable ] Class name
 [ Implements interfacename ]
  [ statements ]
End Class

We saw most of these terms described with the Sub statement earlier today. Here are what the new items mean:

  • MustInherit—Indicates that the class contains methods that must be implemented by a deriving class, as we'll see in Day 9.

  • NotInheritable—Indicates that the class is one from which no further inheritance is allowed, as we'll see in Day 9.

  • name—Specifies the name of the class.

  • statements—Specifies the statements that make up the code for the class.

Here's how we might create a new class named TheClass in a project named Classes (which is in the code for this book):

Module Module1

  Sub Main()

  End Sub

End Module

Class TheClass
    .
    .
    .
End Class

Creating a Data Member

We can now add members to this class, making them Public, Private, or Protected. Public makes them accessible from code outside the class, Private restricts their scope to the current class, and Protected (which we'll see in Day 9) restricts their scope to the present class and any classes derived from the present class. For example, we can add a public data member to our new class just by declaring a variable Public like this:

Module Module1

  Sub Main()

  End Sub

End Module

Class TheClass
  Public ThePublicData = "Hello there!"
    .
    .
    .
End Class

This is not a property of the new class. You need special code to create a property, as we'll see. However, this new data member is accessible from objects of this class like this: TheObject.ThePublicDataMember. By default, data members are private to a class, but you can make them public—accessible outside the object—with the Public keyword as done here.

Creating an Object

Let's see how to access our new data member by creating an object, TheObject, from TheClass. Creating an object is also called instantiating an object, and an object is also called an instance of a class. Unlike the declaration of a simple variable like an Integer, this line of code doesn't create a new object; it only declares the object:

Dim TheObject As TheClass

To create a new object in Visual Basic, you need to use the New keyword:

Dim TheObject As New TheClass

This line creates the new object TheObject from TheClass. You can also create the new object this way:

Dim TheObject As TheClass
TheObject = New TheClass

Some classes are written so that you can pass data to them when you create objects from them. What you're actually doing is passing data to a special method of the class called a constructor. For example, as we'll see tomorrow, you can create a Size object to indicate a Windows form's size, and to make that form 200 by 200 pixels, you can pass those values to the Size class's constructor this way:

Size = New Size(200, 200)

We'll often use constructors when creating objects, but our current example doesn't use one. Here's how we can create a new object—TheObject—using the class TheClass, and display the text in the public data member TheObject.ThePublicDataMember:

Module Module1

  Sub Main()
    Dim TheObject As New TheClass
    Console.WriteLine("ThePublicData holds """ & _
      TheObject.ThePublicData & """")
    .
    .
    .
  End Sub

End Module

Class TheClass
  Public ThePublicData = "Hello there!"
    .
    .
    .
End Class

You can use public data members like this instead of properties if you like, but properties were invented to give you some control over what values can be stored. You can assign any value to a public data member like this, but you can use internal code to restrict possible values that may be assigned to a property (for example, you might want to restrict a property named Color to the values "Red", "Green", and "Blue"). Properties are actually implemented using code in methods, not just as data members. And we'll look at methods next.

Creating a Method

Let's add a method to our class now. This method, TheMethod, will simply be a function that returns the text "Hello there!", and we can call that method as TheObject.TheMethod() to display that text:

Module Module1

  Sub Main()
    Dim TheObject As New TheClass
    Console.WriteLine("ThePublicData holds """ & _
      TheObject.ThePublicData & """")
    Console.WriteLine("TheMethod returns """ & _
      TheObject.TheMethod() & """")
    .
    .
    .
  End Sub

End Module

Class TheClass
  Public ThePublicData = "Hello there!"

  Function TheMethod() As String
    Return "Hello there!"
  End Function
    .
    .
    .
End Class

That's all it takes! Just adding a Sub procedure or function to a class like this adds a new method to the class. Although such methods are public by default, you can make methods private (declaring them like this: Private Function TheMethod() As String), which restricts their scope to the present class. You do that for methods that are used only internally in a class. (To continue the car analogy, such internal methods might be the ones entirely internal to the car, such as the ones that regulate oil pressure or battery voltage.)

Creating a Property

Let's see how to create a property now. You declare properties using Get and Set methods in a Property statement:

[ <attrlist> ] [ Default ] [ Public | Private | Protected | Friend | 
Protected Friend ] [ ReadOnly | WriteOnly ] [Overloads | Overrides ] 
[Overridable | NotOverridable] | MustOverride | Shadows | Shared] 
Property varname([ parameter list ]) [ As typename ] 
[ Implements interfacemember ]
  [ <attrlist> ] Get
   [ block ]
  End Get
  [ <attrlist> ] Set(ByVal Value As typename )
   [ block ]
  End Set
End Property

Here are the parts of this statement that are different from the keywords we've already seen in the Sub statement:

  • Default—Makes this a default property. Default properties can be set and retrieved without specifying the property name.

  • ReadOnly—Specifies that a property's value can be retrieved, but it cannot be modified. ReadOnly properties contain Get blocks but no Set blocks.

  • WriteOnly—Specifies that a property can be set, but its value cannot be retrieved. WriteOnly properties contain Set blocks but no Get blocks.

  • varname—Specifies a name that identifies the property.

  • parameter list—Specifies the parameters you use with the property.

  • typename—Specifies the type of the property. If you don't specify a data type, the default type is Object.

  • interfacemember—When a property is part of a class that implements an interface (covered in Day 9), this is the name of the property being implemented.

  • Get—Starts a Get property procedure used to return the value of a property. Get blocks are optional unless the property is ReadOnly.

  • End Get—Ends a Get property procedure.

  • Set—Starts a Set property procedure used to set the value of a property. Set blocks are optional unless the property is WriteOnly. Note that the new value of the property is passed to the Set property procedure in a parameter named Value when the value of the property changes.

  • End Set—Ends a Set property procedure.

The Set block enables you to set the value of a property, and the Get block enables you to return the value of the property. When you assign a value to a property (as in TheObject.TheProperty = "Hello there!"), the Set block is called, and when you read a property's value (as in Dim strText As String = TheObject.TheProperty), the Get block is called.

You can add code to both blocks to restrict the data stored in a property. Visual Basic passes a parameter named Value to the Set block during property assignments, and the Value parameter contains the value that was assigned to the property when the Set block was called. You usually store the actual value of the property in a private data member in the class.

Here's how this looks in the example. First, you create the new property procedure to handle the property TheProperty, which will hold string data:

Module Module1

  Sub Main()
    Dim TheObject As New TheClass
    Console.WriteLine("ThePublicData holds """ & _
      TheObject.ThePublicData & """")
    Console.WriteLine("TheMethod returns """ & _
      TheObject.TheMethod() & """")
    Console.WriteLine("TheProperty holds """ & _
      TheObject.TheProperty & """")
    Console.WriteLine("Press Enter to continue...")
    Console.ReadLine()
  End Sub

End Module

Class TheClass
  Public ThePublicData = "Hello there!"

  Function TheMethod() As String
    Return "Hello there!"
  End Function

  Public Property TheProperty() As String
    Get

    End Get
    Set(ByVal Value As String)

    End Set
  End Property

End Class

TIP

When you type the first line of a property procedure—that's Public Property TheProperty() As String here—Visual Basic .NET will add a skeleton for the Get and Set procedures automatically.

The next step is to add the code for this property. In this case, we can store the property's value in a private data member named TheInternalData. All we have to do is add code to the Set block to store values in this data member and the Get block to return this data member's value when needed, as shown in Listing 3.12.

Listing 3.12 Classes and Objects (Classes project, Module1.vb)

Module Module1

  Sub Main()
    Dim TheObject As New TheClass
    Console.WriteLine("ThePublicData holds """ & _
      TheObject.ThePublicData & """")
    Console.WriteLine("TheMethod returns """ & _
      TheObject.TheMethod() & """")
    Console.WriteLine("TheProperty holds """ & _
      TheObject.TheProperty & """")
    Console.WriteLine("Press Enter to continue...")
    Console.ReadLine()
  End Sub

End Module

Class TheClass
  Public ThePublicData = "Hello there!"
  Private TheInternalData As String = "Hello there!"

  Function TheMethod() As String
    Return "Hello there!"
  End Function

  Public Property TheProperty() As String
    Get
      Return TheInternalData
    End Get
    Set(ByVal Value As String)
      TheInternalData = Value
    End Set
  End Property

End Class

And that's all we need! Now we've created a new class, given that class a public data member, method, and property, and displayed the data from each of these elements. Here's what you see when you run this example:

ThePublicData holds "Hello there!"
TheMethod returns "Hello there!"
TheProperty holds "Hello there!"
Press Enter to continue...

And that gives us the foundation we'll need when we start working with classes and objects tomorrow.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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