The third key part of an object is its data, or state. In fact, it might be argued that the only important part of an object is its data. After all, every instance of a class is absolutely identical in terms of its interface and its implementation; the only thing that can vary at all is the data contained within that particular object.
Fields are variables that are declared so that they are available to all code within the class. Typically, fields that are declared Private in scope are available only to the code in the class itself. They are also sometimes referred to as instance variables or member variables.
Don't confuse fields with properties. In Visual Basic, a property is a type of method geared to retrieving and setting values, whereas a field is a variable within the class that may hold the value exposed by a property. For instance, you might have a class that has these fields:
Public Class TheClass
Private _Name As String Private _BirthDate As Date End Class
Each instance of the class — each object — will have its own set of these fields in which to store data. Because these fields are declared with the Private keyword, they are only available to code within each specific object.
While fields can be declared as Public in scope, this makes them available to any code using the objects in a manner you cannot control. This directly breaks the concept of encapsulation, as code outside your object can directly change data values without following any rules that might otherwise be set in the object's code.
Consider the Age property shown in the previous section. You'll notice that by using a property, the underlying implementation, even though initially generated, was hidden to the outside world. When you decided to change the implementation to use a dynamically generated age you could change that implementation without changing your interface.
If you want to make the value of a field available to code outside of the object, you should instead use a property:
Public Class TheClass Private _Name As String Private _BirthDate As Date
Public Readonly Property Name() As String Get
Return _Name End Get End Property
Because the Name property is a method, you are not directly exposing the internal variables to client code, so you preserve encapsulation of the data. At the same time, through this mechanism, you are able to safely provide access to your data as needed. Fields can also be declared with the Friend scope, meaning they are available to all code in your project.
Now that you have a grasp of some of the basic object-oriented terminology, you are ready to explore the creation of classes and objects. First you will see how Visual Basic enables you to interact with objects and provides core types (all of which are objects), and then you will dive into the actual process of authoring those objects.
Was this article helpful?