Understanding Object-Oriented Programming Basics


Object-oriented programming will probably be new to many Visual Basic programmers. This section will provide an overview of object-oriented programming, particularly as it relates to the .NET development platform. Object- oriented programming is a substantial topic, so I highly recommend that you do some additional reading to supplement the material provided here. A good place to start is the Visual Studio .NET documentation for Visual Basic, which contains an entire section on object-oriented programming. There are also many books on both object-oriented programming and design patterns, a related subject.

In the simplest terms, an object is an instance of a class in object-oriented languages such as C++, C#, and now Visual Basic .NET. (Classes are described in the section “Using Classes as Containers for Code” later in this chapter.) Objects typically mirror their real-world counterparts: employees, invoices, and purchase orders are all examples of real-world entities that can be modeled as objects in your programs. Objects typically provide both properties, which describe some attribute of the object (for example, an Employee object might have an EmployeeID property), and methods, which allow actions to be taken by the object (for example, an Employee object might expose a Promote method). Object-oriented properties and methods make it easier for programmers to use a given object in ways that relate to the real-world objects that the program is modeling.

In addition to properties and methods, object-oriented programming offers three helpful features: inheritance, polymorphism, and encapsulation.

  • Inheritance is the ability to create new classes that are derived from existing classes. A derived class “inherits” all of the properties and methods of the class from which it is derived (referred to as the parent class). Programmers can then add additional properties and methods to the derived class, or in some cases override the implementation of an existing method inherited from the parent class.

  • Polymorphism lets programmers have identically named methods on different classes derived from the same parent, and it allows the correct method to be executed based on the context of the call. For example, a programmer could define an Invoice class with a Process method. The programmer could then define separate TimeInvoice and MaterialsInvoice classes that are derived from the Invoice class, but define different functionality in their Process methods, hence overiding the functionality exposed by the parent class. When a procedure calls the Process method on one of these derived objects, the proper processing will be executed. The calling procedure doesn’t have to know which kind of Invoice it is dealing with.

  • Encapsulation allows objects to be treated as “black boxes” in that only the properties and methods defined by the programmer as publicly available are visible outside of the object. The internal object state and the implementation of the publicly available methods are hidden by encapsulation. This limited visibility lets developers freely modify the internal state and implementation of their objects, as long as they don’t change the publicly defined interface used to access the object. For instance, an EmployeeList class might expose methods FirstEmployee, NextEmployee, and so on. Internally, such a list could be managed using a simple array, a linked list (in which each item points to the next item in a list), or a database table. To the consumer of the class, it should not matter exactly how the list is maintained internally, as long as the public methods such asFirstEmployee return the correct information.

Using Classes as Containers for Code

Classes are the basic units of object-oriented applications. A class in Visual Basic .NET or C# typically contains property and method definitions, as well as event handlers (a special class of methods). Classes are often grouped into useful collections through the use of namespaces. Namespaces can contain classes and other namespaces. For example, the System.Web namespace defined by the .NET Framework SDK contains not only classes such as HttpRequest,HttpResponse, and HttpServerUtility (which provide the equivalent functionality of the ASP Request, Response, and Server intrinsic objects), but also a number of namespaces, including System.Web.UI, System.Web.Caching, and System.Web.SessionState, each of which also contains classes and/or namespaces.

By using classes as containers for code and namespaces, the .NET architecture makes it very easy to create a rich yet intuitive application hierarchy that can make your code easier to use, debug, and maintain.

Note

When you develop applications in the Visual Studio .NET environment, a root namespace will be created with the same name as your project. If you specify additional namespaces within your code modules, these will become child namespaces of the root namespace. You can change the root namespace, if desired, by right-clicking your project in the Solution Explorer window and selecting Properties. The Root Namespace property appears under Common Properties, General.

Using Inheritance

Now that you know a bit about object-oriented programming, let’s take a look at a simple example of how to put it to use. First, let’s define a class based on a real- world entity—an animal. The following class retrieves a reference to the current HttpContext in order to be able to write output to the browser, and then defines Eat and Sleep methods, each of which writes a message to the browser.

Public Class Animal Dim Context As HttpContext = HttpContext.Current Public Overridable Sub Eat() Context.Response.Write("Yum!<br/>") End Sub Public Overridable Sub Sleep() Context.Response.Write("Zzzzz…<br/>") End Sub End Class 

Next, we’ll create a more specific animal class, Cat, which derives from the Animal class. Note the use of the Inherits keyword on the second line. Inheriting from another class is really that simple. This class will override the behavior of the Eat method but not the Sleep method, as follows:

Public Class Cat Inherits Animal Dim Context As HttpContext = HttpContext.Current Public Overrides Sub Eat() Context.Response.Write("Yum, Yum…Meow, Meow!<br/>") End Sub End Class

You’ll also create a Dog class that derives from Animal and that overrides the Sleep method but not the Eat method, as follows:

Public Class Dog Inherits Animal Dim Context As HttpContext = HttpContext.Current Public Overrides Sub Sleep() Context.Response.Write("Zzzzzz…woofwoofwoofwoof… zzzzzz!<br/>") End Sub End Class

Finally, we’ll use the Cat and Dog classes in the following code. Note that you use the Imports statement to access the members of the Animals namespace without having to fully qualify names (such as Cat instead of Animal.Cat). The sample code for this chapter shows the implementation of Imports.

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim MyCat As New Cat() Dim MyDog As New Dog() MyCat.Eat() MyCat.Sleep() MyDog.Eat() MyDog.Sleep() End Sub 

This code, when added to a Web Form, provides the output shown in the following illustration.

click to expand

Even though you called the same two methods on both the Cat and Dog classes, when you overrode a method of the parent Animal class, you got the behavior that you specified for the particular animal. When you didn’t override, the output shows that you got the behavior inherited from the parent Animal class. You can find the full source code for this example in the practice files for this chapter.

Inheriting from the .NET Base Classes

The preceding example might not seem terribly useful, and admittedly, creating your own Cats and Dogs by inheriting from Animal won’t help you much in your development efforts. Fortunately, the same principles demonstrated in that example apply to the classes that make up the .NET Framework. You can use many of these classes to derive your own specialized classes. You’ll see specific examples of this in Chapter 10.

Inheriting Across Languages

Another nifty feature of the .NET Framework and the CLR is that they allow you to inherit from classes written in other languages. Why is this important? Because it means that development teams can make better use of the existing skill sets of their developers, as well as their company’s existing code base. For example, a company with experienced Visual Basic developers (and existing code in Visual Basic) can have those developers continue to write in Visual Basic .NET. Skilled Java developers can easily make the transition to C# and use the existing class resources created by the Visual Basic developers through inheritance.




Microsoft ASP. NET Programming with Microsoft Visual Basic. NET Version 2003 Step by Step
Microsoft ASP.NET Programming with Microsoft Visual Basic .NET Version 2003 Step By Step
ISBN: 0735619344
EAN: 2147483647
Year: 2005
Pages: 126

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