Website Design United States, Website Design California, Website Designing United States, Website Designing California

Object-Oriented Programming (OOP) Tutorial - Part I - Intro to Classes

Classes are at the very core of Object Oriented Programming. A class defines the properties and methods of an object. Whether you know it or not you have already been working with classes and objects. The new .NET Framework is packed with a large amount of classes you can use. Almost everything in VB.NET is a class. Even the base data types (Integer, Double, Date, etc) are classes and you can use the properties and methods of each.

During this tutorial I mention We or You quite a bit. This means you the reader of this tutorial that is hopefully following along and creating these classes. When I say They I mean the users (programmers not end users) of these classes. When you write classes you are doing the job of the Author (no not writing books). When you use these classes in your program you are the developer (They).

You can think of a Class as a blueprint of an object. It maps out all the properties and methods and what each property and method will do.

Lets start with the beginnings of a class. Open Visual Studio .NET and create a new Console Application called ShapeClass. A Solution will be created with a module and you should see the following code:

Module Module1
Sub Main()

End Sub
End Module

We currently don't have any classes. To add a class click Project > Add Class and name it Square.

Public Class Square

End Class

Now lets give this class some basic properties and methods. Since this is just an introduction I will keep it a simple class. Classes are based on real life objects so now we must think what a square has. The first thing I think of is the four sides and since it is a square all four side are the same. So it will have a Length property. Going back to grade school math you could also calculate the Parameter by Length * 4 and the Area by Length squared.

Lets start with the Length property. There are four (4) main types of properties: read/write, write once, read only, and parameter.  Read and writer properties can be read and changes however many times as you need. Write once properties can be set (changed) only once and read however many times you need. Read only properties cannot be set but can be read however many times you need.  I will explain parameter properties later on in this tutorial.

Now we will focus on the Length. Ask yourself can a length be negative or even zero? No! Can it have a decimal? Yes! So we have to program that. Since there can be a decimal lets declare it as a Double type. So we will need a module level variable to keep track of the length and a Length property to read/write that variable.

Private mdblLength As Double

Public Property Length() As Double ' this data type and
Get

End Get

Set(ByVal Value As Double) 'this data type must match
' Value is the what they want to change it to
End Set
End Property

As you will notice the property has a Get and Set. The Get is called when you want (read) the value and the Set is called when you change the value. The method of having a private variable with public properties or sub/functions the get/set the value is called Encapsulation. This means you can determine what they see and control the value of the variable. If you simply made it public then they could just get and set the value all they want to whatever they want. The Get will simply return the mdblLength but the Set is a little more complicated. It cannot be negative or zero so you must check for that. Q: What do I do if the number is invalid? A: That is up to you. You could simply ignore it or throw an Exception.
Ignore it:

Public Property Length() As Double
Get
Return mdblLength
End Get

Set(ByVal Value As Double)
If Value > 0 Then
mdblLength = Value
Else
Throw New ArgumentException("Length must be greater than zero (0)")
End If
End Set
End Property

Throw an Exception:

Public Property Length() As Double
Get
Return mdblLength
End Get

Set(ByVal Value As Double)
If Value > 0 Then
mdblLength = Value
Else
Throw New ArgumentException("Length must be greater than zero (0)")
End If
End Set
End Property

Ultimately the decision is yours. Also the type of exception and message you display are also your decision but both should be applicable to the situation.
Now for the methods. Both Perimeter and Area calculate something which I might want to know. So both will be functions.

Public Function Perimeter()
Return mdblLength * 4
End Function

Public Function Area()
Return mdblLength ^ 2
End Function

The final code should look something like:

Public Class Square
Private mdblLength As Double
Public Property Length() As Double
Get
Return mdblLength
End Get
Set(ByVal Value As Double)
If Value > 0 Then
mdblLength = Value
Else
Throw New ArgumentException("Length must be greater than zero (0)")
End If
End Set
End Property

Public Function Perimeter() As Double
Return mdblLength * 4
End Function

Public Function Area() As Double
Return mdblLength ^ 2
End Function
End Class

How about another example? As I mentioned earlier there are Parameter properties and I said I would show you one. Parameter properties can be read/write, write once, or read only as well. It all depends on the situation. Lets continue with another class called Triangle. As mentioned before, a triangle has a list of its sides and has three (3) sides in all. To store this you need an array of doubles. Q: How do I know which side they want to set when it is one property? A: They also supply the index (0 to 2) of the side they wish to change. Now you have to check that they set it to a valid number and supply a valid index. Again what you do if they supply invalid values is up to you.

Private mdblSides(3) As Double
Public Property Sides(ByVal Index As Integer) As Double
Get
If Index > -1 And Index < 3 Then
Return mdblSides(Index)
Else
Throw New IndexOutOfRangeException("Index must be from 0 to 2")
End If
End Get
Set(ByVal Value As Double)
If Index > -1 And Index < 3 And Value > 0 Then
mdblSides(Index) = Value
ElseIf Value <= 0 Then
Throw New ArgumentException("Side must be greater than zero (0)")
Else
Throw New IndexOutOfRangeException("Index must be 0 to 2")
End If
End Set
End Property

A triangle also has a Perimeter and Area but calculating them is different then a square. Remember the area of a triangle is Base * Height / 2 but we don't know the base or height. We do know the base is one of the sides and the height is a perpendicular line going from where the other two lines meet to the base. So you can either have a new property to keep track of the base and another for the height or make one of the elements of the side the base and have another for height. I will do the second option and have a public constant to show which element is the base. There will also be an example of a read only property. A read only property must be declared with the ReadOnly keyword.

Public Const BaseIndex = 0

Private mdblHeight As Double

Public ReadOnly Property Base() As Double
Get
Return mdblSides(BaseIndex)
End Get
End Property

Public Property Height() As Double
Get
Return mdblHeight
End Get
Set(ByVal Value As Double)
If Value > 0 Then
mdblHeight = Value
End If
End Set
End Property

Then you can calculate the Perimeter and Area.

Public Function Perimeter() As Double
Return mdblSides(0) + mdblSides(1) + mdblSides(2)
End Function

Public Function Area() As Double
Return mdblSides(BaseIndex) * mdblHeight / 2
End Function

You have been wonder when the object is first created that all the variables are zero which is invalid. Also is there something that is called when I create an object of the class. Well yes the New sub is called when you create an object of the class and you would put the code in there. Which brings me to method overloading. Method overloading is a method with the same name but different parameter list. Lets stick with the Sub New example in the triangle. We will have two, one with no parameters and another will all the three sides and height.

#Region "Constructor(s)"
Public Sub New()
SetDefaults()
End Sub

Public Sub New(ByVal BaseLength As Double, ByVal SecondLength As Double, _
ByVal ThirdLength As Double, ByVal TriangleHeight As Double)
SetDefaults()
Me.Sides(0) = BaseLength
Me.Sides(1) = SecondLength
Me.Sides(2) = ThirdLength
Me.Height = TriangleHeight
End Sub
#End Region

Private Sub SetDefaults()
Dim pintCount As Integer
For pintCount = 0 To 2
mdblSides(pintCount) = 1
Next
mdblHeight = 1
End Sub

You may be wonder what the Region... End Region is. It's simply a way of organizing and identifying your code. You may also be wondering why I set the defaults in both of the Sub New. Just because they supply the parameters doesn't mean they will supply valid values. So the second Sub New sets the defaults and then tries to set the values.
Your final code for the Triangle class should look similar to:

Public Class Triangle
Public Const BaseIndex = 0

Private mdblSides(3) As Double
Private mdblHeight As Double

#Region "Constructor(s)"
Public Sub New()
SetDefaults()
End Sub

Public Sub New(ByVal BaseLength As Double, ByVal SecondLength As Double, _
ByVal ThirdLength As Double, ByVal TriangleHeight As Double)
SetDefaults()
Me.Sides(0) = BaseLength
Me.Sides(1) = SecondLength
Me.Sides(2) = ThirdLength
Me.Height = TriangleHeight
End Sub
#End Region

Private Sub SetDefaults()
Dim pintCount As Integer
For pintCount = 0 To 2
mdblSides(pintCount) = 1
Next
mdblHeight = 1
End Sub

Public ReadOnly Property Base() As Double
Get
Return mdblSides(BaseIndex)
End Get
End Property

Public Property Height() As Double
Get
Return mdblHeight
End Get
Set(ByVal Value As Double)
If Value > 0 Then
mdblHeight = Value
End If
End Set
End Property

Public Property Sides(ByVal Index As Integer) As Double
Get
If Index > -1 And Index < 3 Then
Return mdblSides(Index)
Else
Throw New IndexOutOfRangeException("Index must be from 0 to 2")
End If
End Get
Set(ByVal Value As Double)
If Index > -1 And Index < 3 And Value > 0 Then
mdblSides(Index) = Value
ElseIf Value <= 0 Then
Throw New ArgumentException("Side must be greater than zero (0)")
Else
Throw New IndexOutOfRangeException("Index must be 0 to 2")
End If
End Set
End Property

Public Function Perimeter() As Double
Return mdblSides(0) + mdblSides(1) + mdblSides(2)
End Function

Public Function Area() As Double
Return mdblSides(BaseIndex) * mdblHeight / 2
End Function
End Class

If you want to do the same thing for the Square:

#Region "Constructor(s)"
Public Sub New()
mdblLength = 1
End Sub

Public Sub New(ByVal SideLength As Double)
mdblLength = 1
Me.Length = SideLength
End Sub
#End Region

Now lets test! Go back to the Module. Inside Sub Main() declare two variables, one of type Square and another of type Triangle.

Dim a As Square
Dim b As Triangle

Their names don't really matter. Notice when you type a = New Square( you get two options. The same is true for the Triangle variable. Set the Square with an invalid length (a = New Square(-1)) and then output the Length (Console.WriteLine(a.Length)). If you have your Square to throw an exception for an invalid length then it should throw an exception. If not then the length should be 1.

Try
a = New Square(-1)
Console.WriteLine ("Length = " & a.Length.ToString())
Catch ex As ArgumentException
Console.WriteLine (ex.Message)
End Try

Then play around with the numbers and try the Perimeter and Area functions to see if it works.


WEB DESIGN INDIA
42 B Malviya Nagar , New Delhi-110017

Skype: manmeetsi
Email: support.webdesignindia@gmail.com
Tel: 91-011-40502005, 9810067295

 















 


© 2008-2009 dotnet4all.com