Section 3.3. Defining a Class

   

3.3 Defining a Class

When you define a class you describe the characteristics and behavior of objects of that type . In VB.NET, you describe characteristics with member fields , also known as properties .

 Class Dog    Private weight As Integer  ' weight is an integer    Private name As String     ' the Dog's name as text 

Member fields are used to hold each objects state. For example, the state of the Dog is defined by its current weight and name. The state of an Employee might be defined by (among other things) her current salary, management level, and performance rating. Chapter 8 includes a full discussion of member fields.

You define the behavior of your new type with methods . Methods contain code to perform an action.

 Class Dog    Private weight As Integer  ' weight is an integer    Private name As String     ' the Dog's name as text  Public Sub bark( )   'code here to bark   End Sub  

The keywords Public and Private are known as access modifiers , which are used to specify what classes can access particular members. For instance, public members can be called from methods in any class, while private members are visible only to the methods of the class that defines the member. Thus, objects of any class can call bark on a Dog, but only methods of Dog have access to the weight and name of the Dog. Access modifiers are discussed in Chapter 8.

A class typically defines a number of methods to do the work of that class. A Dog class might contain methods for barking, eating , napping, and so forth. An Employee class might contain methods for adjusting salary, submitting annual reviews, and evaluating performance objectives.

Methods can manipulate the state of the object by changing the values in member fields, or a method could interact with other objects of its own type or with objects of other types. This interaction among objects is crucial to object-oriented programming.

For example, a Dog method might change the state of the Dog (e.g., weight), interact with other Dogs (e.g., bark, sniff, etc.), or interact with People (e.g., beg for food). A Product object might interact with a Customer object, a Video object might interact with an EditingWindow object.

Designing a good VB.NET program is not unlike forming a good team; you look for players ”or objects, in the case of a program ”with different skills to whom you can assign the various tasks you must accomplish. Those players cooperate with one another to get the job done.

In a good object-oriented program, you will design objects that represent things in your problem domain. You will then divide the work of the program among your objects, assigning responsibility to objects based on their ability.

   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net