You are on page 1of 106

Course Code:

IT202 OOP
Using VB .Net
Lecturer:
F.Masimba
Bsc (Hons) information Systems
Msc Information Systems.
PhD Student Information systems, Vaal University of Technology(SA)
Object Oriented Programming
(OOP)
Outlines
 What is Object-Oriented Programming ?
 Procedural vs. Object-Oriented Programming
 OO Programming Concepts
 Concept of Objects and classes
 UML Class Diagram
 Visibility Modifiers and Accessor Methods
 Full Example
Let’s think about the concept of Class
and Object
Classes & Objects !
What is Class ?

o Classes are constructs that define objects of the


same type.
o “Class” refers to a blueprint. It defines the variables
and methods the objects support.

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea
Class & Object
Class & Object
Class & Object
Class & Object
Thinking to build class …

o A Java class uses variables to define data fields and methods to


define behaviors.
o Additionally, a class provides a special type of methods, known as
constructors, which are invoked to construct objects from the
class.
Thinking to build class …
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
How to build my class?

Is a reserved word The identifier of class


Must be as any variable
Access_modifiers class
class_name {
// variables = attributes
Access_modifiers
class_name(par1, par2, …)
{ Always, the class has
a method called constructor
} which gives initial values
// behavior = methods to the attributes of class

}
Class Members

o A class can have three kinds of members:


 fields: data variables which determine the status of the class or
an object
 methods: executable code of the class built from statements. It
allows us to manipulate/change the status of an object or access
the value of the data member
 nested classes and nested interfaces
How to instatiate object?

Reserved word

class_name object_name = new class_name (arg1, arg2, …);

The name of The Values based


class, which name on the
you want to of parameters of
instatiate an object constructor
object of it.
UML Class Diagram

UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125
Practices for the undergrad IT202 class

Group 1 Group 2 Group 3


Compare between Detect 3 classes from Diffrenciate between
constructor and your bedroom and Class & Object
methods in class. 2 objects.

Group 4 Group 5 Group 6


Draw the UML Class Draw the UML Class Thinking to build
Diagram of Course Diagram of Student Animals class.
class. class.
18

Course Details
 Assignments & Presentations
 2 assignments all typed and submitted through google
classroom or via my email: bmukhalela@cuz.ac.zw
 1: Group Presentation

 Tests & Exam


 2 Test both in-class
 Final Exam

 Course Work contributes 30% - Exam contributes 70% of


final grade
What is a program and What is a
programming language
 An organized set of instructions that enable a computer
to behave in a pre-determined order.

 A programming language is a formal way of


communicating instructions to a computer.
 Various types of programming languages which include
Java, C, C++, Visual C++, C#, VB to mention a few.
.NET Infrastructure
The .Net Base Class Library provides support for:

1. user interface
2. data access
3. database connectivity
4. cryptography
5. web application development
6. numeric algorithms
7. network communications

The CLR provides the appearance of an application


virtual machine so that programmers need not
consider the capabilities of the specific CPU that
will execute the program
The CLR (Cont…)
The CLR also provides other important services such as
1. security
2. memory management
3. exception handling
Object Oriented Programming
 There are five requirements to OO languages.
 Objects – provide data encapsulation, coupling and
cohesion
 Modular, Structured
 Abstraction – facilitates parameterization (making
something a function of something else)
 Code Hiding,
 Encapsulation, Information Hiding, Cohesion
 Polymorphism
 Multiple Access Methods, Multiple Response Actions
 Inheritance - facilitates polymorphism and encapsulation
 Organization, Code-reuse
Object Components
The Object
 Data
 Members
 Properties
 Behavior
 Methods
 Events
The IDE – Visual Studio – Creating
a new Proj
The Beginning…
A VB.Net program basically consists of the
following parts:
Namespace declaration
A class or module
One or more procedures
Variables
The Main procedure
Statements & Expressions
Comments
Hello World!
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
Identifiers
An identifier is a name used to identify a class, variable, function, or any
other user-defined item. The basic rules for naming classes in VB.Net are as
follows:

A name must begin with a letter that could be followed by a sequence of


letters, digits (0 - 9) or underscore.

The first character in an identifier cannot be a digit.

It must not contain any embedded space or symbol like ? - +! @ # % ^ &
* ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

It should not be a reserved keyword


Variables
 A variable is a storage area of the computer's memory.
 With programming languages, what you are basically doing
is storing things in the computer's memory, and manipulating
this store.
 Hence, If you want to add two numbers together, you put the
numbers into storage areas and instruct Visual Basic to add
them.

Question: Is there a difference between a Variable


and an Identifier?
Data Types
 The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
 Data Types in VB .Net include
 Boolean – True or False
 Integer – 4 Bytes (Signed)
 Date – 8 Bytes
 Decimal – 16 Bytes
 Double – 8 Bytes
 Long – 8 Bytes (Signed)
 Char – 2 Bytes (Unsigned)
 String – Depends on the platform
 Byte – 1 Byte (Unsigned)
 Short – 2 Bytes (Signed)
Variable Declaration in VB .Net
 The Dim statement is used for variable declaration and
storage allocation for one or more variables. Short for
Dimension.
Example:
Dim number1 As Integer

number1 – Identifier
Integer – Data Type
Dim – Reserved / Keyword
Variable Initialization in VB .NET
 Variables are initialized (assigned a value) with an
equal sign followed by a constant expression
Example:
Dim name as String
name = “John”
Exercise
Write a simple program that declares variables number1
and number2, and performs the arithmetic operations
below

- (the minus sign)


* (the multiplication sign)
/ (the divide sign)
+ (Addition)

And displays the results using a Message Box


References
 http://www.tutorialspoint.com/vb.net
 http://www.homeandlearn.co.uk/NET
Course Code:
IT202 OOP
Using VB .Net
- Lecture 2

Lecturer:
Braiton U Mukhalela BSc CIS (AU) Hon BScIS
36
(UNISA),MComIS(GZU).
Constant Variables
 Constants refer to fixed values that the program
may not alter during execution.
 The fixed values are also called Literals
 Constants can be of any data type but remain
fixed throughout the execution of a program

Example:
Const PI as Double = 3.14
Enumerations
 An enumeration is a set of named integer constants
 A Variable that declared with specific values allocated to it.
 An enumerated type is declared using the Enum statement.
 The Enum statement declares an enumeration and defines the
values of its members.
 The Enum statement can be used at the module, class,
structure, procedure, or block level.
Example
Enum Colors
red = 0
orange = 1
yellow = 2
End Enum
Console.WriteLine("The Color Red is : " & Colors.red)
More on Operators
Arithmetic: +, -, /, *, ^ , \ , Mod

Comparison:
=, > , <, >= , <= , <>

Logical: AND, OR, NOT, XOR

Binary Shift Operators: >>, <<


Decision Making When
Programming
If...Then Statement
If condition Then
[Statement(s)]
End If
If...Then...Else Statement
If(boolean_expression)Then
'statement(s)
Else
'statement(s)
End If
Conditional Statements – If…..ElseIf
Dim s As String = Console.ReadLine()

' Check input with If, Elseif and Else.


If s = "cat" Then
Console.WriteLine("You like cats")
ElseIf s = "dog" Then
Console.WriteLine("You like dogs")
Else
Console.WriteLine("No choice made")
End If
Nested If…
If (a = 100) Then
If (b = 200) Then
Console.WriteLine("Value of a is 100
and b is 200")
End If
End If
Select…Case
A Select Case statement allows a variable to be
tested for equality against a list of values.
Select expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Example
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case Else
Console.WriteLine("Invalid grade")
End Select
Nested Select….
Select a
Case 100
Console.WriteLine("This is part of outer case ")
Select Case b
Case 200
Console.WriteLine("This is part of inner
case ")
End Select
End Select
Looping
 Basicidea is to execute a block of
statements for a finite number of times
Do….While
It repeats the enclosed block of statements
while a Boolean condition is True or until
the condition becomes True. It could be
terminated at any time with the Exit Do
statement.
Example:
Do While|Until (condition)……Loop

Do…….Loop While|Until (Condition)


For……Next
 Repeats a group of statements a specified number
of times and a loop index counts the number of
loop iterations as the loop executes.

Example:
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
 You can also specify the number of steps
While….End
Example:

While a < 20
Console.WriteLine("value of a:
{0}", a)
a=a+1
End While
Nested Loops
For counter1 [ As datatype1 ] = start1 To end1 [ Step
step1 ]
For counter2 [ As datatype2 ] = start2 To end2
[ Step step2 ]
<statements>
Next [ counter2 ]
Next [ counter 1]
Loop Control – Exit and Continue
Exit
Terminates the loop or select case statement and transfers
execution to the statement immediately following the loop
or select case.

Continue
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Group Presentation Question 1
Write a Visual Basic Program that prompts a user to
enter a character, length and width of a box. For
example *, Length – 4 and width 4 should give result:

****
****
****
****
Group Presentation Question 2
Write a Visual Basic Program that allows a
user to enter any positive integer for an
infinite number of times and terminates
execution by entering a negative value. After
execution the program should print the sum,
average, maximum and minimum of the
values entered.
Group Presentation Question 3
Write a visual basic program that accepts temperature in degrees
Celsius and converts it to Fahrenheit given that

Temp (F) = Temp (C) * (9 / 5) + 32

Where Temp (F) is temperature in Fahrenheit and


Temp (C) is temperature in Degrees.

The program should accept and convert temperatures input by a user


for an infinite number of times, and all temperatures to be converted
should fall in the range 5 degrees to 30 degrees Celsius.
Strings
 InVB strings are basically represented
as an array of characters declared using
the string keyword.

 Creating a string
Example:
Dim myString as String = “Artwell”
Properties and methods of the
string class
String.compare(String A, String B) – Integer (0) True
String.concat(String A, String B) – String
.length – Integer
.contains(String A) – Boolean
IndexOf(String A) – Integer
toCharArray() – Character Array
ToLower() – lowercase
toUpper() – Uppercase
.substring(Integer) - String
String Concatenation
Dim name = “Akim”
Dim surname = “Ndlovu”
Dim result = name & “ ” & lastname

You can technically also use the + operator however the


problem lies when therz ambiguity
Dim age as String = “10”
Dim x = 5
Dim result = x + age However if you use string
concatenation it will work
Arrays
 An array stores a fixed-size sequential collection of elements
of the same type
 All arrays consist of contiguous memory locations
 Arrays use an indexing method to access data locations

To declare an array:
Dim myArr(10) as Integer
‘This declares an array of 10 Elements
Note: There is a difference between the array size and the upper
bound
Array Initialization
Arrays can be initialized statically or
dynamically through the use of a loop

Example:
Dim intData() As Integer = {12, 16, 20, 24,
28, 32}
Dynamic Arrays
Arrays are static in order to make them dynamic
use Re-Dim

Example:
Dim myMarks(5) as Integer
ReDim myMarks(10) as Integer
ReDim preserve myMarks(10) as Integer
Multi-Dimensional Arrays
 Similar to a table

Example Declaration of a 2-Dimensional Array


Dim myArr(5,5) as Integer Can also be initialized
statically or dynamically.
Subscripts are in the form of rows and columns
Useful Array Methods
Array.getUpperBound(Array)
Array.Reverse(Array)
Array.Sort(Array)
<arrname>.getLowerBound(Dimension)
<arrname>.getLength(Dimension)
Array.Clear(Array_name, index, length)
Array.IndexOf(Array)
Further Research
What is a Jagged Array and how can
it be applied in VB .Net
Question
Write a simple program that accepts the
number of seconds and display the
result in the form of hours, minutes and
seconds for example 60 seconds => 0
Hours 1 minute and 0 Seconds
Question
Write a program that accepts an integer value and displays
the corresponding month.

For example given:


1..January
2..February
3..March

12..December
Question
Given two one dimensional arrays A and B
which are sorted in ascending order. Write a
program to merge them into a single sorted
array in ascending order.
Functions and Procedures
 A procedure or function is a group of
statements that perform a specific task
when called.
 After the procedure or function has
executed, the control of the program
returns to the statement calling the
procedure or function
Functions and subs
There is a difference between
functions and procedures
Function return a value when
called whilst procedures do not.
Declaring a function
public function myFunct(num1 as integer, num2 as integer)
as Integer
……Statements
end function

You can return a value by assigning the


result to the function name or by using the
return keyword.
Passing parameters to a Function
Parameters can be passed to a
function by Value or By Reference
using the keywords
ByVal or ByRef
Procedures
 Sub procedures do not return a value, for
example our main sub procedure.
Procedures are declared as follows:

Sub getSalary(ByVal mySal as Decimal)


….statements
End Sub
Objectives of Lecture
 Learn how to handle program anomalies
 Learn how to convert from one data type to
another
 Understand the different error types
 Learn How to read from and write to a file
Exception Handling
 An exception is a runtime or unexpected
error generated during the execution of a
program

 To handle exceptions in VB .Net the


following key words are used

 Try…..Catch….Finally and Throw


Divide by Zero Exception
Try
result = num1 / num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught:
{0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
The Exception Class
Exception: Parent of all Exceptions
IOException: handles I/O errors
InvalidCastException: Typecasting errors
DividebyZeroException: Divide by Zero
IndexoutofrangeException: Index out of
range
User-defined Exceptions
 You can define your own exceptions in VB .Net, by
inheriting from the ApplicationException class

Example
Public Class TempIsZeroException : Inherits
ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
User Defined Exception
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If

Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Type Casting in VB .Net
 Involves the conversion of a data type from one form to
another
 To do so you can use the Ctype function and specify
the original variable and the resultant data type

Example : Ctype(myVar, Integer)


Convert.to<Datatype>(Value)

Research on Widening and Narrowing in VB.Net


Types of errors
Runtime
Compile Time
Logical
 A form of persistent storage
File Handling VB .Net
 The namespace that deals with files is System.IO using classes
StreamReader and StreamWriter
 Using defines garbage collection for your program so you don’t
have to write code yourself
Example
Using reader As StreamReader = New StreamReader("file.txt")
Do While (True)
Dim line As String = reader.ReadLine()
If line Is Nothing Then
Exit Do
End If
Console.WriteLine(line)
Loop
Useful File function in VB .Net
 File.readAllText(path)
 File.writeAllText(path)
 File.appendAllText(path)
 File.Exists(path)
 File.create(path)

Example
Dim array As String() = File.ReadAllLines("file.txt")
Dim line As String
For Each line In array
Dim length As Integer = line.Length
Next
Question
1. Write a program that counts the
number of a’s in a text file.
2. Write a program that stores a
username and password in a file
secret.ini, and uses the credentials
stored to authenticate a user
Next Week
Visual Basic Event driven
programming
QUESTION
Classes and Objects
 A Class is a blueprint that defines what an object of that
class will consist of as well as the operations that can
be performed on the object.

Example
Class <class_name>

…..[Statements]
End Class
Instantiating a class
 A class is instantiated using the New keyword in visual
basic.
Example
Class myClass
……….[Statements]
End Class

Sub Main(){
Dim newMyClass as myClass = new myClass()
}
Class Constructors and
Destructors
 A class constructor is a special member Sub of a class that is
executed whenever we create new objects of that class. A
constructor has the name New and it does not have any
return type.

 Classes have a default constructor that does not take any


parameters, however if you need to define parameters you
can do so to initialize your class. Such constructors are
known as parameterized.
NB: Constructors take the name of the class
Destructors
 A destructor is a special member Sub of a class that is
executed whenever an object of its class goes out of
scope.

 A destructor has the name Finalize and it can neither


return a value nor can it take any parameters.

 A Destructor can be very useful for releasing resources


before coming out of the program like closing files and
releasing memories
Example
Protected Overrides Sub Finalize()
'creating a Destrustor
End Sub
Inheritance
 Inheritance is the concept that when a class of
objects is defined, any subclass that is defined
can inherit the definitions of one or more
general classes.

 inheritance suggests an object is able to inherit


characteristics from another object
Inherits keyword
 Classes in VB.NET support only single
inheritance, and Object is the ultimate base
class for all classes

 A Classinherits from a another class using


the inherits keyword
Method Overriding
 Overrides is used by derived classes (classes that
inherit from a base class) to replace the original
method from the base class with one of its own,
which must match the same method signature.
 For overriding to work, the methods in the base
class must be declared as OVERRIDABLE
Polymorphism
 Polymorphism is one of the crucial features of
OOP. It means " one name multiple form". It
is also called as overloading which means the
use of same thing for different purposes.

 Polymorphicmethods are declared using the


overloads keyword
How to use classes in .Net
 Simply go to the project menu -> click add
class
Question
 Design a class person with attributes name, surname,
gender, address and id_number.
 Design a separate class that defines student and lecturer
as a person.
 The student class has methods that instantiate students
properties such as name, surname…
 The lecturer has attributes faculty and department as
well as methods that instantiate lecturer properties such
as name, surname…
VB.Net - Dialog Boxes
 There are many built-in dialog boxes to be used in
Windows forms for various tasks like opening and
saving files, printing a page, providing choices for
colors, fonts, page setup, etc., to the user of an
application. These built-in dialog boxes reduce the
developer's time and workload.
 There are many built-in dialog boxes to be used in
Windows forms for various tasks like opening and
saving files, printing a page, providing choices for
colors, fonts, page setup, etc., to the user of an
application. These built-in dialog boxes reduce the
developer's time and workload.
 The RunDialog() function is automatically
invoked when a user of a dialog box calls its
ShowDialog() function.
 The ShowDialog method is used to display all the
dialog box controls at run-time. It returns a value
of the type of DialogResult enumeration. The
values of DialogResult enumeration are:
DialogResult Enumerations
 Abort - returns DialogResult.Abort value, when
user clicks an Abort button.
 Cancel- returns DialogResult.Cancel, when user
clicks a Cancel button.
 Ignore - returns DialogResult.Ignore, when user
clicks an Ignore button.
 No - returns DialogResult.No, when user clicks a
No button.
DialogResult Enumerations
 None - returns nothing and the dialog box
continues running.
 OK - returns DialogResult.OK, when user clicks
an OK button
 Retry - returns DialogResult.Retry , when user
clicks an Retry button
 Yes - returns DialogResult.Yes, when user clicks
an Yes button
common dialog class inheritance
Adding Menus and Sub Menus
in an Application
 letus study the following concepts:
 Adding menus and sub menus in an application
 Adding the cut, copy and paste functionalities in a
form
 Anchoring and docking controls in a form
 Modal forms
 the Menu, MainMenu, ContextMenu, and
MenuItem classes were used for adding menus,
sub-menus and context menus in a Windows
application.
 Now, the MenuStrip, the ToolStripMenuItem,
ToolStripDropDown and
ToolStripDropDownMenu controls replace and
add functionality to the Menu-related controls of
previous versions. However, the old control
classes are retained for both backward
compatibility and future use.
 Let us create a typical windows main menu bar
and sub menus using the old version controls first
since these controls are still much used in old
applications.
 Following is an example, which shows how we
create a menu bar with menu items: File, Edit,
View and Project. The File menu has the sub
menus New, Open and Save.

You might also like