The goal of this lesson is not to try and explain object oriented programming (OOP). There are entire books and classes dedicated to that. Nor is it to try and convince you that OOP is any better or worse then procedural programming. That's a debate I'm simply not going to get involved in. The purpose of this lesson is to give the beginning ASP.NET developer a basic introduction to objects and some sample code that illustrates creating, instantiating, and using an object from an ASP.NET web page.
There are several reasons to use objects when programming. Every book or class on OOP will tell you that using objects makes code easier to reuse, maintain, and extend, but objects can also make the code you write easier to understand. Instead of creating an array or collection containing information about a product that a user is about to order from a web store, you can simply create a product object. Then instead of needing to remember that the third array item represents the product's price, you can simply check the price property of the object to get its price.
This is the main reason why I use objects when I'm writing code. Once you get used to using them... objects can makes reading and thinking about the code much easier.
Before you can build something, you generally need to have a plan on how to build it. For example, before a building is constructed, an architect is hired to draft a blueprint. The blueprint contains the information needed to construct the building.
The same is necessary when building an object in a computer. This blueprint is called a class. You create a class in VB by using the class keyword. Below is a simple class for creating a dog object.
Public Class Dog Public Dim Name As String Public Dim BirthDate As DateTime Public Dim Weight As Integer Public Sub New(Name As String, BirthDate As DateTime, Weight As Integer) MyBase.New Me.Name = Name Me.BirthDate = BirthDate Me.Weight = Weight End Sub Public Function Speak() Speak = "Woof Woof!" End Function End Class |
The code above doesn't actually do anything for us except define what a dog is for the computer. A class tells the computer what properties an object has and what it can do. If we created a dog using this blueprint, it would have a name, a birth date, a weight and it would know how to speak. That's it. The dog that we created would be what is called an instance of the dog class listed above. That's why creating an object from a class is called instantiation. Here's a code listing showing how you'd do this in VB:
Dim myDog As Dog myDog = New Dog("Spot", New Date(2000, 11, 12), 65) |
You'll notice that we create our dog the same way we'd create any other variable in VB. That's because VB (and the .NET Framework) are all object oriented to begin with. So now that VB knows about our dog class, creating a dog object is the same as creating an integer, string, or date object.
Setting properties and calling methods of our dog object is accomplished the same way it is with any other object:
' Set the Breed property myDog.Breed = "dalmation" ' Call the Speak method lblMyDogSays = myDog.Speak() |
You'll see more samples of playing around with the object in the sample code you can download at the bottom of this lesson.
This is all well and good, but at the moment all this cool stuff doesn't help us much in the reuse department because we can only use our dog object on pages on which we define the class. On other pages, there is no way for VB/ASP.NET to know anything about our dog. We can solve this problem by placing our object in a separate .vb file, creating a namespace to contain our object, compiling the new file, and then adding the output to our application's /bin directory. This process makes it available to any page in our ASP.NET application because ASP.NET is set to automatically watch the /bin folder and use whatever it finds there. As a result, we can gain access to our class from any page within our ASP.NET application by simply including the following line at the top of the page:
<%@ Import Namespace="Animal" %> |
The name "Animal" is simply what I called the namespace in my .vb file:
Imports System Imports Microsoft.VisualBasic Namespace Animal Public Class Dog Public Dim Name As String Public Dim BirthDate As DateTime ... ... ... End Class End Namespace |
The compilation part is pretty easy. For VB the command will look something like this:
vbc /t:library
/out:.\object_namespace.dll object_namespace.vb
That assumes you're at a command line prompt in the directory containing the source file and that the VB compiler is in your path. If not you'll need to adjust your commands appropriately. After compiling, all you need to do is move the resulting object_namespace.dll file to your application's /bin directory where it will automatically be picked up and available to be included by your .aspx pages.
You can download the code from this lesson from here: objects.zip (3.5 KB). It includes the dog class, some sample usage, and the alternate version that places the class into the animal namespace and compiles it. I've included the source (object_namespace.vb) and compiled versions (object_namespace.dll) in case you have any trouble compiling it.
A quick note... my naming conventions for these files are less then optimal. Something like animal.vb would be much better. I'm only using the object prefix because the files go with my object lesson and it makes things simpler for me. In the real world files should be named for what they are. Sorry about that...
How many times have you been working with an object or ASP.NET control and wanted it to behave a little differently or do something that it couldn't? What if you could make a new version that automatically got all the features of the old version and only changed or added what you wanted? You can... and it's all thanks to the fact that .NET is object oriented.
Like last time, the goal of this lesson is not to try and explain object oriented programming (OOP). There are entire books and classes dedicated to that. Nor is it to try and convince you that OOP is any better or worse then procedural programming. That's a debate I'm simply not going to get involved in. We're simply trying to teach you enough to be dangerous. ;) All kidding aside, if you're looking to learn more about OOP, I'm sure there are far better resources and authors who are much more adept at explaining it elsewhere. The goal of this lesson is simply to introduce you to inheritance and the benefits it can offer you as an ASP.NET developer.
Everything in the .NET world is an object. While this is relatively obvious in some cases (like with controls) it's not so obvious in others. Even simple types like integers and strings are implemented as objects in .NET. This means that everything in .NET shares a common base. More complex objects are built based on simpler existing ones. The coolest part of all this is that you too can create new objects based upon existing ones and these new objects will automatically get all the functionality of the object they're built upon. This feature is called inheritance. In the same way you inherit your good looks and winning personality from your parents, your new object inherits its default properties and methods from it's parent object.
Just to keep things simple, I'm going to illustrate inheritance using the same example we used in our Creating and Using Objects lesson. If you haven't yet read it, I suggest you do so now.
In our objects lesson, we built a class that enabled us to create and manipulate the properties of an object that represented a dog. In the real world I can't think of too many applications for that except maybe for a dog shelter or veterinarian. The analogy gets sort of weak from here on in, but bear with me. Now let's assume that we're dealing with a very specialized vet that only deals with one type of dog... I'm going to use Dalmations (mainly because they're cute!). Now, since we know we're going to be dealing with Dalmations a lot, wouldn't it be nice if we didn't have to specify that the dog's breed is Dalmation every time we created a dog object... and maybe Dalmations sound a little different then your average dog... maybe it's more of an 'Arf Arf!' as opposed to the more generic 'Woof Woof!'. Okay... I give... enough of this... let's see some code.
Public Class Dalmation : Inherits Dog Public Dim NumberOfSpots As Integer Public Sub New(Name As String, BirthDate As DateTime, Weight As Integer) MyBase.New(Name, BirthDate, Weight, "Dalmation") End Sub Overrides Public Function Speak() Speak = "Arf Arf!" End Function End Class |
There are four main things I want you to notice in the class listing above:
1.
First of all,
notice the Inherits Dog
declaration after the class name.
This tells us that this new object is based on our dog object. As a result it
gets all the attributes of a dog automatically. A good way to think of this
relationship is to use the "is a kind of" test. A Dalmation is a kind
of dog. If you're trying to stretch things too far, this test will fail. After
all, it doesn't make sense to try and build a cat based on our model for a dog.
A tabby is not a kind of dog. You'd want to go farther up to a more generic
(hypothetical) animal object if you wanted to start building a cat.
2. I've hard coded the breed type. Since we're dealing with a Dalmation object, there's no question as to the breed of dog involved and so there's no need for us to be setting it every time we create a dog.
3. I've added a new attribute. Since Labradors and Poodles rarely have spots, it doesn't make sense to build an attribute to count them into our base dog object. Dalmations, on the other hand, do have spots, so I've added a way to keep track of them.
4. Finally, I've overridden the default Speak method and replaced it with a version modified to more accurately reflect, the way our dog sounds. (Please note that I've never owned a Dalmation so while I know they have spots... I've got no clue if they go 'Woof Woof!', 'Arf Arf!', or make any noise at all.)
Just like last time, one of the main reasons to create objects at all is so we can reuse them. If we've got to include the code that tells us how to create them every time, then what good is it? So just like in our object lesson, we'll create a library (.dll file) and add it to our application's /bin directory. Once our object is there, we have access to it from any page in our ASP.NET application.
The command is a little more complex then last time because we need to reference the existing Dog object that our new Dalmation object is based upon. The compiler can't build a Dalmation which is based on a Dog unless it knows about a Dog. So in order to compile our new Dalmation sucessfully, we've got to tell it where it can find out about our Dog. For VB the command will look something like this:
vbc /t:library
/reference:c:\inetpub\wwwroot\bin\object_namespace.dll
/out:inheritance_namespace.dll inheritance_namespace.vb
That assumes you're at a command line prompt in the directory containing the source file and that the VB compiler is in your path. If not you'll need to adjust your commands appropriately. After compiling, all you need to do is move the resulting inheritance_namespace.dll file to your application's /bin directory where it will automatically be picked up and available to be included by your .aspx pages.
Once the libary is in place, your code can be as simple as this:
<%@ Page Language="VB" %> <%@ Import Namespace="Dogs" %> <script language="VB" runat="server"> Sub Page_Load(Source As Object, E As EventArgs) Dim myDog As Dalmation myDog = New Dalmation("Spot", New Date(2000, 11, 12), 65) ... End Sub </script> |
You can download the code that accompanies this lesson from here: inheritance.zip (8.3 KB). It includes the code listed above as well as all supporting files. For the libraries, I've included the source and compiled versions in case you have any trouble compiling it.
A quick note... once again my naming conventions for these files are less then stellar. I'm just trying to keep my files from each lesson grouped together. In the real world files should be named for what they are. Sorry about that...