Vbnet Lecture 45 Classes Function and Subroutines1
-
Upload
vinod-chandran -
Category
Documents
-
view
220 -
download
0
Transcript of Vbnet Lecture 45 Classes Function and Subroutines1
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
1/11
SCC Intro to.NET
Lecture 4&5 Classes, Function, and Subroutines
Including Labs Examples
Classes
A class is simply a representation of a type of object; think of it as the object'sblueprint or template. Just as a single blueprint can be used to build multiplebuildings, a class can be used to create multiple copies of an object.An object is a specific instance of a class, and includes the characteristics of thatclass.
The class that defines an object has its own failed, properties, methods, and events(sometimes called members) that are passed on to all instances of that class.Visual Basic programs are built with objects such as forms or controls. Objects canalso be used to represent real-world things, such as a person, a computer, or evensomething more abstract, such as a bank account.
For example, a class that represents a Student might have properties such asStudentNumber, StudentName and StudentGroup, methods such as RegisterStudent,and events such as StudentFailed. Once you instantiate a Student object, you canaccess its properties, methods and events just as you would with an object such asTextBox
Class declarationPublic Class ClassName
You can define the class members (failed, properties, properties) here
End Class
You can define the class members (failed, properties, properties) between Classand End Classkey words
Instance data membersInstance data members include member variables and constants. Membervariables are also calledfields.
A data member specific to an instance of the class is called an instance datamember. When you add instance data members to a class, you specify thelevel ofaccess by setting the access modifiers.
Example:Publ i c Cl ass St udentPr i vat e name As St r i ngPr i vat e no As I nt egerPr i vat e mark( 3) As I nt eger
End Cl ass
T. Mohamed Ezeddin L4&5-1
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
2/11
SCC Intro to.NET
Access modifiers or [accessibility]
Public Accessible everywhere Accessible everywherePrivate Accessible only within the class itselfProtected Accessible only by classes which inherit from the class
Procedure
A procedure is a self-contained block of code that can be run from
other blocks of code
Functions and Subs
There are two kinds of procedures: functionsand subroutines(sometimes called subs). A function returns a value to theprocedure that called it, whereas a sub simply executes code.
Sub declaration
A Subprocedure is a series of Visual Basic statements enclosed by the Sub andEnd Sub statements.
[accessibility] Sub SubName( [argumentlist] )
' Statements of the Sub procedure go here
End Sub
Example:
Publ i c Sub SayHel l ow( )MessageBox. Show( "Hel l ow Wel come t o My Pr ogr am")
End Sub
Example2:
Publ i c Sub Regi st er St udent ( ByVal Sno As I nt eger , ByVal Sname AsSt r i ng)
name = Snameno = Sno
MessageBox. Show( "The st udent has succef ul l y Regi st er ed")End Sub
Notes
The argument list are optional in the first example I didnt add any
argument to the sub declaration
Arguments aredata passed to procedures
T. Mohamed Ezeddin L4&5-2
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
3/11
SCC Intro to.NET
You can pass argumentsByVal orByRef
ByVal: The procedure cannot modify the value of the original variable
ByRef: The procedure can modify the value of the original variable
ByVal is the default in Visual Basic .NET
Syntax for adding argument after the sub or function name :([ByVal| ByRef] argumentname As datatype)
ExampleProcedureName (ByVal Name As String)
Function declaration
A Functionprocedure is a series of Visual Basic statements enclosed by theFunction and End Function statements. Functionprocedures are similar to Subprocedures, but functions can return a value to the calling program.
[accessibility] Function name[(argumentlist)] As datatype' Function statements, including optional Return' statement
End Function
Example:
Publ i c Funct i on sumOf( ByVal no1 As I nt eger, ByVal no2 As I nt eger) As I nt eger Di m s As I nt egers = no1 + no2Return s
End Funct i on
Example2:
Publ i c Funct i on St udent Tot al Mar k( ) As Doubl eDi m i As I nt eger = 0Di m tot As Doubl e = 0For i = 0 To mark. Length - 1
t ot = t ot + mar k( i )Next
T. Mohamed Ezeddin L4&5-3
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
4/11
SCC Intro to.NET
Return tot
End Funct i on
Calling theProcedure
Subs are called when a line of code that contains the name of thesub is added to the program, as in the following example.
Di spl ayResul t s
Functions are different, because functions not only execute code,
they also return a value. For example, imagine a function calledStudentTotalMarkthat returns a Doubleindicating the totalmarks of student. You call this function by first declaring a
variable in which to store the return value, and then assigning thereturned value to the variable for later use, as shown below.
Di m t ot al As Doubl et ot al = StudentTotalMark()
Using the New Keyword
The Newkeyword in Visual Basic .NET used to create new object instances. Insome of the code you've seen today, Newwas used to demonstrate the creation of aninstance of a class. Each class file in your project contains members, which aresimply the methods, variables, properties, and structures that make up the class. Touse a class's members, you must create a variable of the type of class you're tryingto work with.
When you use the Newkeyword, you're creating a variable of a specified type andsetting its members to their default values. In the case of a base type, such as aninteger, creating a new instance of a variable of type integer defaults the variable'svalue to zero. In the case of a class, all variables are set to their default values. TheNewkeyword is used all the time in .NET. Because you're writing code in class files,you must normally create an instance of that class before you attempt to access anyof its members. The following code creates a new instance of Cl ass1and makes itavailable to the variable X:
Di m x As Cl ass1 = New Cl ass1' Both of t hese decl ar at i ons are equi val ent i n VB. NETDi m x As New Cl ass1
After you've declared Xas a new instance of the class Cl ass1, you have access tothe members of Cl ass1using the dot notation. For example, if Cl ass1has a publicstring variable named f i r st Name, you can access it as follows:
T. Mohamed Ezeddin L4&5-4
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
5/11
SCC Intro to.NET
Set t he var i abl ex. f i r st Name = " J ason"
Ret r i eve t he var i abl eMessageBox. Show( x. f i r st Name)
Each time you use the Newkeyword, you're creating an instance of a class. Thevariable holds the instance, which then has access to all the members in the classinstance you've declared.
Lab Example 1
1-Create a new Windows Application Project2-Chose Add Class from project menu3-Change the file name toTest Ref Val .vb in the dialog after that press Add
A new class will created in the fileTest Ref Val .vb with the following contents:
Publ i c Cl ass Test Ref Val
End Cl ass
4-Add the following fields and methods to the class
Publ i c Cl ass Test Ref ValPubl i c Sub Doubl Count ( ByVal number As I nt eger )
number = number + numberEnd SubPubl i c Sub Doubl Count 2( ByRef number As I nt eger )
number = number + numberEnd SubPubl i c Sub Test()
Di m myNumber As I nt eger = 10Doubl Count ( myNumber )MessageBox. Show( myNumber )Di m numAs I nt eger = 10Doubl Count 2( num)MessageBox. Show( num)
End SubEnd Cl ass
5-Open the Form1 and double click the Form1 (in design view ) the code view will open. In the Form1_Load sub procedure add the following Code
Pr i vat e Sub For m1_Load( . . )Di m t As New TestRef Valt . Test ( )
End Sub
T. Mohamed Ezeddin L4&5-5
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
6/11
SCC Intro to.NET
6- Press F5 to run your application
7-Add the following class culc in the same file TestRefVal.vb
Note:you can add more than 1 class in any .vb file after the End Class key word of
the pervious class
Publ i c Cl ass cul cPubl i c Funct i on sumOf ( ByVal no1 As I nt eger , ByVal no2 As I nt eger ) _
As I nt egerDi m s As I nt egers = no1 + no2Retur n s
End Funct i onPubl i c Sub SayHel l ow( )
MessageBox. Show( "Wel come t o My Pr ogr am")End Sub
End Cl ass8-. In the Form1_Load sub procedure add or modify the following Code
Pr i vat e Sub For m1_Load( . . )Di m t As New TestRef Valt . Test ( )Di m c As cul cc. SayHel l ow( )Di m sum As I nt eger sum = c. sumOf ( 30, 40)MessageBox. Show( "t he sum : " & sum)
End Sub
T. Mohamed Ezeddin L4&5-6
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
7/11
SCC Intro to.NET
Lab Example 2
1-Create a new Windows Application Project2-Chose Add Class from project menu3-Change the file name to Student.vb in the dialog after that press Add
A new class will created in the file Student.vb with the following contents:
Publ i c Cl ass St udent
End Cl ass
Note you can write the code for your class in any other f i l e t hat has . vbextension
4-Add the following fields and methods to the class
Publ i c Cl ass St udentPubl i c name As St r i ngPubl i c no As I nt egerPr i vat e mark( 2) As I nt eger
Publ i c Sub showSt udent I nf o( ) MessageBox. Show( "Student name: " + name + "Student number : " + no)
End Sub
Publ i c Sub Regi st er St udent ( ByVal Sno As I nt eger , ByVal Sname As St r i ng)name = Snameno = SnoMessageBox. Show( "The st udent has succef ul l y Regi st er ed")
End Sub
Publ i c Sub AddSt udentMar ks( ByVal m1 As Doubl e, ByVal m2 As Doubl e, _ByVal m3 As Doubl e)
mar k( 0) = m1mar k( 1) = m2mar k( 2) = m3
End Sub
Publ i c Funct i on St udent Tot al Mar k( ) As Doubl eDi m i As I nt eger = 0Di m tot As Doubl e = 0For i = 0 To mark. Length - 1
t ot = t ot + mar k( i )
NextRet ur n tot
End Funct i on
End Cl ass
T. Mohamed Ezeddin L4&5-7
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
8/11
SCC Intro to.NET
5-Open the Form1 and double click the Form1 (in design view ) the code view will open. In the Form1_Load sub procedure add the following Code
Pr i vat e Sub For m1_Load( . . )Di m s As New St udentDi m n As I nt eger = 20Di m s t r As St r i ng = "Mohamed"
s. Regi st er St udent ( n, st r )s. showSt udent I nf o( )s. AddStudent Marks( 70, 90, 80)Di m t otal As Doubl et ot al = s. St udent Tot al Mar k( )st r = s. name
MessageBox. Show( "t he st udent " & st r & " t otal mark=" & t ot al )
End Sub
6- Press F5 to run your application
T. Mohamed Ezeddin L4&5-8
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
9/11
SCC Intro to.NET
Lab Example 3
1- Add new form to the project you create in Example 12- In the Form2 design add the following controls
Control Property Value
Name frmStudentInfoForm2
Text Student InformationLabel1
Text Name:
Label2Text Number:
TextBox1Name txtName
TextBox2Name txtNumber
GroupBox1Text Marks
Label3
Text VB.Net:Label4
Text Java:Label5
Text Oracle Developer:NumericUpDown1
Name numMark1NumericUpDown2
T. Mohamed Ezeddin L4&5-9
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
10/11
SCC Intro to.NET
Name numMark2NumericUpDown3
Name numMark3Label6
Text Total Marks:
Name txtTotalTextBox3
ReadOnly True
Name btnTotalButton1
Text Calculate total marks
Name btnAddButton2
Text Add Student
Name btnShowButton3
Text Show Student Info
3- Chose View Code from the popup menu after you press any where in the designview to view the code of frmStudentInfo
4- Add the following declaration in the general declaration of frmStudentInfo
Di m st u As St udent
5- Add t he f ol l owi ng code t o t he bt nAdd Cl i ck event
Pr i vat e Sub bt nAdd_Cl i ck( )st u = New St udent
Di m n As I nt egerDi m s t r As St r i ngn = CI nt ( t xtNumber . Text )st r = t xt Name. Textst u. no = nst u. name = st rDi m mar k1, mar k2, mar k3 As Doubl emar k1 = numMar k1. Val uemar k2 = numMar k2. Val uemar k3 = numMar k3. Val uest u. AddStudent Marks( mark1, mark2, mark3)
End Sub
6-
Add the f ol l owi ng code to t he bt nShow Cl i ck event
Pr i vat e Sub bt nShow_Cl i ck( . . )Tr y
st u. showSt udent I nf o( )Catch ex As Except i on
MessageBox. Show( ex. Message)EndTr y
End Sub
T. Mohamed Ezeddin L4&5-10
-
7/24/2019 Vbnet Lecture 45 Classes Function and Subroutines1
11/11
SCC Intro to.NET
7- Add t he f ol l owi ng code t o t he bt nAdd Cl i ck event
Pr i vat e Sub bt nTot al _Cl i ck( )
Tr yDi m tot As Doubl et ot = st u. St udent Tot al Mar k( )t xtTot al . Text = t ot
Catch ex As Except i onMessageBox. Show( ex. Message)
EndTr y
End Sub
8-
Change the startup form to frmStudentInfo (from project properties)9- Press F5 to Run your application
Best wishes,
T. Mohamed Ezeddin
For more study materials visit my web site
http://issite.wordpress.com
T. Mohamed Ezeddin L4&5-11
http://issite.wordpress.com/http://issite.wordpress.com/