Kamis, 03 April 2008

VB.Net Implementing OOP - Chapter 2

IMPLEMENTING OOP

OBJECTIVES

· Implement procedures and functions
· Implement delegates
· Implement classes in VB.Net
· Work with events
· Implement error handling

Procedures and Functions

Procedures and functions are:
· Code snippets written for a particular process, which is to be executed many times
from different parts of the program.
· Avoid repetition of the same code in many places for the same purpose.
· Save time and memory.

A procedure is declared as Sub in VB.Net and cannot be declared inside another procedure

Defining Procedures

Syntax

Protected Friend Protected Friend Private Sub subname [(argumentlist)}
‘ Statements
End Sub

An Example

Sub MySub (ByVal S1 As String)

Return

End Sub

Return and Exit Sub

· The Exit Sub statement causes an immediate exit from a Sub procedure.
· A Return statement can also be used to immediately exit the procedure.
· It is also possible to combine the Exit Sub and Return statements.


An Example

Sub Perimeter(ByVal Len As Double, ByVal Wid As Double)
Dim Peri As Double ' Declare local variable.

If Len = 0 Or Wid = 0 Then
' If either argument = 0.
Exit Sub ' Exit Sub immediately.
End If

Peri = 2*(Len + Wid ) ' Calculate Perimeter of rectangle.
System.Console.WriteLine(Peri)
' Print Perimeter to Immediate window.
End Sub

Function Procedures

· A Function procedure can be defined inside a module, class, interface, or
structure, but not inside another procedure.
· Function procedures are Public, by default.
· Function Procedures return values, whereas Sub Procedures cannot return a value
to the calling procedure.

sutan
SYNTAX

[ ] [{ Overloads Overrides Overridable NotOverridable MustOverride Shadows Shared }]
[{ Public Protected Friend Protected Friend Private }] Function name[(arglist)] [ As type ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function

An Example

Function Compute (ByVal J As Integer) As Double
' ...
Compute = 4.22
' ...
Exit Function
' ...
End Function

Function Procedures

· A Function procedure can be defined inside a module, class, interface, or
structure, but not inside another procedure.
· Function procedures are Public, by default.
· Function Procedures return values, whereas Sub Procedures cannot return a
value to the calling procedure.

Syntax

[ ] [{ Overloads Overrides Overridable NotOverridable MustOverride Shadows Shared }]
[{ Public Protected Friend Protected Friend Private }] Function name[(arglist)] [ As type ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function


An Example

Function Compute (ByVal J As Integer) As Double
' ...
Compute = 4.22
' ...
Exit Function
' ...
End Function

Another Example

This example simultaneously assigns a return value andexits the function.

Function Compute(ByVal J As Integer) As Double
' ...
Return 4.22
' ...
End Function



Calculating Absolute Value

Function Absolute(ByVal Argument1 As Double) As Double
If Argument 1 < 0 Then
' Evaluate argument.
Exit Function ' Exit to calling procedure.
Else
Absolute= Abs(Argument 1) ' Return absolute value.
End If
End Function

Passing Arguments

· When an argument is passed by value, only a copy of a variable is passed. If the
procedure changes the value, the change is reflected only in the copy.
· VB provides the ByVal keyword to indicate that an argument has been passed by
value.


An Example

Sub Twice(ByVal num As Integer)
num = num * 2
System.Console.WriteLine(“The value is {0}”,num)
End Sub
Sub Calculate()
Dim x As Integer
x = 4
System.Console.WriteLine(“The value here is {0}”, x)
Twice (x)
System. Console.WriteLine(“The double is {0}”, x)
End Sub

Output
4
8
4

Passing Arguments by Reference

· Passing arguments by reference gives a procedure access to the original value of
the variable in its memory location.
· Variables are passed by reference using the ByRef keyword.

An Example

Sub Twice (ByRef num As Integer)
num = num * 2
System.Console.WriteLine(“The value is {0}”, num)
End Sub
Sub Calculate()
Dim x As Integer
x = 4
System.Console.WriteLine(“The value is {0}”, x)
Twice(x)
System.Console.WriteLine(“The new value is {0}”, x)
End Sub

Passing Mechanism - An Example

If an argument is declared with ByRef, the calling code can force the mechanism to pass by value by enclosing the argument name (in parentheses) in the call.

An Example:

Sub Task (ByRef Num1 As Integer)
' Code that makes changes to Num1
End Sub
Sub Main
Call Task((N1)) ‘Pass N1 ByVal even though declared ByRef
End Main

Optional Arguments

· Optional arguments are indicated by the Optional keyword in the procedure
definition.
· Every optional argument in the procedure definition must specify a default value,
which must be a constant expression.
· If the Optional keyword is used, all subsequent arguments in the argument list
must also be optional and be declared using the Optional keyword.

The following syntax shows a procedure declaration with an optional argument:

Sub proc_name(ByVal arg1 As type1, Optional ByVal arg2 As type2 = defaultvalue)

When one or two optional arguments are omitted in the argument list, successive commas are used to mark their positions. The following procedure call supplies the first and fourth arguments but not the second or third:

Call proc_name(arg1, , , arg4) ' Leaves out arg2 and arg3.

Delegates

o A delegate is used for executing different methods at runtime using a general
method name.


Syntax to declare a delegate is:

Delegate Function (param1 as type, param2 as type) As

Example of Delegate

Delegate Function Deleg(ByVal Var as Integer) As Integer

Module M1

Function Flg (ByVal Var as Integer) As Integer
Flg=Var
End Function

Function Flg1 (ByVal Var as Integer) As Integer
Flg1=Var * 10
End Function

Example of Delegate (Cont…)

Sub Main( )

Dim d1 as Deleg
d1 =AddressOf Flg
Dim int val as Integer =d1(5)
System.Console.WriteLine(intval)
d1=AddressOf Flg1
intval=d1(10)
System.Console.WriteLine(intval)

End Sub
End Module

Implementing Classes

Module1.vb

Module Module1

Public Class Class1
Dim var1 As Integer
Public Sub first()
Var1 = system.Console.ReadLine()
System.Console.writeLine(“You entered {0}”,var1 )
End Sub
End Class

Sub Main()
Dim trial As New Class1()
trial.first()
End Sub

End Module


C:\WINNT\System32\cmd.exe

Microsoft windows 2000 [Version 5.00.2195]
Copyright 1985-2000 Microsoft Corp.
C:>module1
12
You entered 12
C:>

Constructors

· Constructors are special methods that allow us to instantiate an object of a
particular type and set the initial state of this object.
· In VB, the constructor method is always called New regardless of the name of the
type.

An Example

Class Course
Sub New(ByVal CourseID As Integer)
…….
End Sub
End Class

Destructors

· Destructors can be implemented in VB.net using the Dispose method.

The following code disposes off an object that has a Dispose method:

Public Sub Dispose()
Bridget_Jones.Dispose
Bridget_Jones= Nothing
' Insert additional code.
End Sub

Events

o To add an event to a class, use the Event keyword.

Create an event as follows:

Public Event MyEvent(ByVal info As String)
To cause an event to fire, we add a RaiseEvent statement in the program at the point where the event has to be raised.

Example of an Event

Public Sub Function1()
RaiseEvent MyEvent(“Info”)
End Sub


WithEvents Keyword

Private WithEvents myObjects1 As MyClass
Private WithEvents myObjects2 As MyClass

Private Sub OnMyEvent (ByVal Info As String)
Handles myObjects1.MyEvent, myObjects2.MyEvent

System.Console.WriteLine(Info)
End Sub


Error Handling

Public Sub TryExample()
Dim x As Integer = 5 ' Declare variables.
Dim y As Integer = 0
Try ' Set up structured error handling.
x /= y ' Cause a "Divide by Zero" error.
Catch
y = 0 ' Catch the error.
Finally
System.Console.WriteLine(“Tried to divide by zero”) ‘ End Try
End Sub

Tidak ada komentar: