Xtreme Visual Basic Talk

Xtreme Visual Basic Talk (http://www.xtremevbtalk.com/)
-   Tutors' Corner (http://www.xtremevbtalk.com/tutors-corner/)
-   -   Object Oriented Programming (http://www.xtremevbtalk.com/tutors-corner/264076-object-oriented-programming.html)

MikeJ 06-07-2006 10:20 PM

Object Oriented Programming
Table of Contents
A Note before Starting
You've taken out the installation CDs from the package; you've gone through the lengthy install process, and now what? You've opened up the program, sat through the loading screen, and you're ready to go do … what? "Hello World is a great place to start," you think. You hit New Project on the start screen, and up pops the new application wizard. Hit a few more options, and up comes the designer. You go to the code window and see … Public Class! Whoa! What's this?!

Or, let's say you are an experienced programmer who has been around the block a few times. You've done it all; you started with COBOL, you've done C/C++, and may have used VB6 at some point in the past. But now, you are required to move to .NET, and have encountered a similar problem as described above.

In either case, no matter what your experience is in VB, you have to start somewhere. In the move, such a big deal was made about OOP, and now it's time to actually learn it. Where do you start? Right here, of course. :)

This tutorial, for the lack of a better word, is designed to discuss the different aspects of OOP, and hopefully explain why it is so beneficial to use OOP in coding. At the moment, it stops at inheritance basics, but it should provide you with help in understanding some of the more interesting aspects of the .NET platform, or any OOP-supported language.

Enjoy, and don't hesitate to jump right in!

MikeJ 07-01-2006 11:03 PM

A Brief History of Programming
A Brief History of Programming
Before starting any object-oriented programming, it is important to understand where the concept comes from. There have been many important "benchmarks" in coding styles, evolving until finally reaching the current pinnacle, OOP.

The first stage is the so-called cryptic programming stage. Those who have been programming for decades probably remember this stage fondly: it was the first era of programming. Computers were new and it took a lot of training to become a proficient programmer, and of course, there was a lack of knowledgeable coders. Think punch cards. Job security was rather high, as there were so few eligible applicants, and thus, programmers had little reason to change.

Of course, no company likes being held hostage by their employees, so a move was made to make programming more accessible. This stage is considered the spaghetti-code programming stage. This was the era of BASIC; it was relatively easy to learn a language and all one needed was a compiler to do some neat stuff (especially if you were just a hobbyist). This was when the use of GoSub and GoTo was used frequently. It was a time of free programming, when everyone and his or her mother had the chance to program. It should come as no surprise that the market was flooded with some inferior products with massive memory leaks and critical errors. (Interestingly enough, this was also when Microsoft was creating their first Operating System! :chuckle:.)

The third stage was more modern; the structured programming stage was the time that programming languages started to settle down, and people started to use the one-task-one-module belief. That is, each module has its own purpose and only does that one thing. No more random jumping around to different line numbers; the program followed a set order of events and reliability improved greatly. Astute readers will note that this stage closely resembles VB6 or C/C++.

The fourth stage is a type of intermediate stage between structured programming and OOP and is known as the event-driven programming stage. This stage was marked by greater user interactivity with the program (think of all the general Object events from VB6, such as _Click() or _KeyDown()). This made development easier for the programmer due to increased ease-of-use, but it came at the cost of using "pure" programming models.

Finally, we reach the object-oriented programming stage. This is where programming currently is at; each object can have methods, properties, events. This stage has seen the greatest reliability and reusability of code yet. You could create a class with methods you frequently use, drop it into a project, and suddenly use it all over again. You could create a user class and use it any manner of web projects. The possibilities go far beyond anything previously possible with earlier incarnations of Visual Basic.

MikeJ 12-14-2006 12:03 AM

Classes vs. Objects
1 Attachment(s)
I know I said this was object-oriented programming. So why am I talking about classes? The answer to this question is that all objects are classes. (Mind-blowing, huh?) The way to separate the difference between objects and classes is quite easy. An object has an IS-A relationship, while a class has a HAS-A relationship.

A car IS-A vehicle, while a dog HAS-A tail. The car would be an object declared as type Vehicle, while the dog would have a member that IS-A tail. However, Fido IS-A dog. The dog class is the base template for all dog objects, so when we declare Fido as a dog, Fido is an object. Since Fido IS-A dog, Fido HAS-A tail.

IS-A = object
HAS-A = class

"Class" and "object" are sometimes used interchangeably. However, classes describe the structure of objects, while objects are instances of classes. Each instance is an exact copy of its base class. Because an object is an "instance" of a class, the act of creating an object is called instantiation.
To describe it better, a class is a blueprint, and an object is a building based on that blueprint.

To understand it, we can use an example. Open up Visual Studio, and create a new Windows Application. Go to the File menu, click Add New Item, and select "Class". A blank class window should show up. Change the name from Class1 to Vehicle. This should be what comes up:
Public Class Vehicle 'This is an empty class End Class
We will start by creating a constructor. A constructor is a special method inside each class that tells the class what to do when it is instanced. The instantiation of a class occurs when a new instance of a class is declared. In VB.NET, this is accomplished with the New sub.

Change your class so it looks like this:
Public Class Vehicle #Region " Constructors " 'The default constructor Public Sub New() 'Tell the user that the new sub is being called. MessageBox.Show("This is a new vehicle object", "Object Oriented Programming") End Sub #End Region End Class
Notice two things. The first is the Region called "Constructors". I usually create these different regions to keep the code window nice and neat, and as you can have multiple constructors (see below), it's nice to keep them all in one place. The second is the code in the New sub. This should fire every time a new object is declared.

To test this out, we can add some code to the MainForm_Load() method on our form:
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Declare a vehicle called Car and instance it Dim Car As Vehicle Car = New Vehicle() ' 'Declare a vehicle called Truck and instance it Dim Truck As Vehicle Truck = New Vehicle() End Sub
Run it. You'll notice that you get two identical MessageBoxes that tell you that you have created a new vehicle object. That's nice, right? Wouldn't it be better to at least let it tell you what type of vehicle it is? We can: just overload a new constructor.

Change the class to:
Public Class Vehicle Protected _VehicleType As String #Region " Constructors " 'The default constructor Public Sub New() 'There was no parameter passed, so let's say the vehicle is a "vehicle" _VehicleType = "vehicle" ' 'Alert the user MessageUser() End Sub ' 'Another constructor that accepts a parameter Public Sub New(ByVal VehicleType As String) 'We've been passed a parameter, so let's store that in a private variable 'for later use _VehicleType = VehicleType ' 'Alert the user MessageUser() End Sub #End Region Private Sub MessageUser() 'Tell the user what type of class it is MessageBox.Show("This object is a " & _VehicleType, "Object Oriented Programming") End Sub End Class
That's a lot! What does it mean? The first line "Protected _VehicleType As String" means that this is a variable that can be used anywhere inside the class, or any subclass (we'll get to this topic later). The default constructor has been modified to take into account the storage variable, and if there's no parameter passed, it sets the variable to "vehicle".

What about that second constructor? It's known as an overloaded constructor because it is a New sub, but has a parameter attached to it. We take the passed value and assign it to our protected variable. Let's see what this new class does. Modify MainForm_Load to be the following:
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Declare a vehicle called Car and instance it Dim Car As Vehicle Car = New Vehicle("car") ' 'Declare a vehicle called Truck and instance it Dim Truck As Vehicle Truck = New Vehicle("truck") ' 'Declare a vehicle called Van and instance it Dim Van As Vehicle Van = New Vehicle() End Sub
Notice how the MessageBox has been changed to reflect this addition. Car and Truck are shown to be their respective types, but because nothing was passed to the Van instantiation call, it defaults to "vehicle".

MikeJ 12-14-2006 12:07 AM

A Note on Variable Scope
What about that "Private Sub MessageUser()" line from our previous example? It's a private sub, as the name states, but try to access it from outside the Vehicle class. In the MainForm_Load() sub, try adding Van.MessageUser. You should get a build error that states 'Vehicle.Private Sub MessageUser()' is not accessible in this context because it is 'Private'. Try the same thing with the _VehicleType variable and you should get a similar result.

As the error suggests, you can't access certain types of class members from outside of the class itself.

The four types of variables we have used so far are:
Public variables. These can be access directly from the class. We choose not to use this with OP by convention. Rather we create Properties (we'll get into this later) to adjust variables directly, or use Get/Set methods.

Private variables. These can be accessed only within the class. Private variables cannot be accessed by any subclasses or other class. These are ideal whenever you have a class you know will not be inherited. Also, these are good for storing data that should not be exposed publicly.

Protected variables. These can be accessed by the class or any subclass that is inherited. These are what I personally use because if you design a subclass later, you don't have to change your base class code later. This is a good catchall private storage method.

Local variables. These are created by the Dim statement. These exist for the duration of the location in which they are declared. For example, if you Dim x As Int32 in Form_Load(), it will only exist in the Form_Load() method.

These four access types are also used frequently in sub/function/property headings, and thus are not limited to just variables. For more information on access types, see the MSDN article.

All times are GMT -6. The time now is 08:18 PM.

Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2018, vBulletin Solutions, Inc.
Search Engine Optimisation provided by DragonByte SEO v2.0.15 (Lite) - vBulletin Mods & Addons Copyright © 2018 DragonByte Technologies Ltd.
All site content is protected by the Digital Millenium Act of 1998. Copyright©2001-2011 MAS Media Inc. and Extreme Visual Basic Forum. All rights reserved.
You may not copy or reproduce any portion of this site without written consent.