Home > Articles

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account