Objects andVB Classes

48
Objects andVB Classes ISYS 350

description

Objects andVB Classes. ISYS 350. What Is an Object?. Objects are key to understanding object-oriented technology. There are many examples of real-world objects: your dog, your desk, your television set, your bicycle. - PowerPoint PPT Presentation

Transcript of Objects andVB Classes

Page 1: Objects andVB Classes

Objects andVB Classes

ISYS 350

Page 2: Objects andVB Classes

What Is an Object?• Objects are key to understanding object-oriented

technology. There are many examples of real-world objects: your dog, your desk, your television set, your bicycle.

• Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, wagging tail). Bicycles also have state (current gear, current speed) and behavior (changing gear, applying brakes).

• Identifying the state and behavior for real-world objects is the key to model an object.

Page 3: Objects andVB Classes

What Is a Class?• In the real world, you'll often find many individual

objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model.

• Each bicycle was built from the same set of blueprints and therefore contains the same components.

• In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

• A class is the blueprint from which individual objects are created.

Page 4: Objects andVB Classes

Entities

• An entity is a person, place, object, event, or concept in a business environment about which the organization wishes to maintain data.– Person: Employee, Student, patient– Place: Warehouse, Store– Object: Product, Machine.– Event: Registration, Sale, Renewal– Concept: Account, Course

• Physical existence:• Customer, student, product, etc.

• Conceptual existence:• Bank accounts, sale

Page 5: Objects andVB Classes

Entity Type

• A collection of entities that share common properties or characteristics.

• An entity type represents a collection of entities.

• A business environment may involve many entity types.– University: Faculty, Student, Course– Department, Employee, Dependent– Sales person, Customer, Order

Page 6: Objects andVB Classes

Adding a Class to a Project

• Project/Add Class– *** MyClass is a VB keyword.

• Steps:– Adding properties

• Declare Public variables in the General Declaration section

• Property procedures: Set / Get

– Adding methods• Function• Procedure

Page 7: Objects andVB Classes

Procedures

. Sub procedure:

Sub SubName(Arguments)

End Sub– To call a sub procedure SUB1

• CALL SUB1(Argument1, Argument2, …)

Page 8: Objects andVB Classes

Call by Reference Call by Value

• ByRef– The address of the item is passed. Any changes

made to the passing variable are made to the variable itself.

• ByVal– Default– Only the variable’s value is passed.

Page 9: Objects andVB Classes

Demo: call a procedure; Input argument; output argument

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim mySum As Double Call myProcedure() Call AddTwoNum(InputBox("Enter num1:"), InputBox("Enter num2:")) Call ReturnSumByArgument(InputBox("Enter num1:"), InputBox("Enter num2:"), mySum) MessageBox.Show("The sum is: " + mySum.ToString) End Sub Private Sub myProcedure() MessageBox.Show("You are calling a procedure!") End Sub Private Sub AddTwoNum(ByVal Num1 As Double, ByVal Num2 As Double) Dim Sum As Double Sum = Num1 + Num2 MessageBox.Show("The sum is: " + Sum.ToString) End Sub Private Sub ReturnSumByArgument(ByVal Num1 As Double, ByVal Num2 As Double, ByRef Sum As Double) Sum = Num1 + Num2 End Sub

Page 10: Objects andVB Classes

Function

• Private Function tax(Bval salary as Double) As Double

• tax = salary * 0.1

• End Function

– Or• Private Function tax(ByVal salary as Double) As

Double

• Return salary * 0.1

• End Function

Page 11: Objects andVB Classes

Using a Function

Dim Salary As Double Salary = InputBox("Enter salary: ") MessageBox.Show("Tax is" + tax(Salary).ToString)

Private Function tax(ByVal salary) As Double tax = salary * 0.1 End Function

Page 12: Objects andVB Classes

Class Code Example

Public Eid As String

Public Ename As String

Public salary As Double

Public Function tax() As Double

tax = salary * 0.1

End Function

Page 13: Objects andVB Classes

Using a Class

• Define a class variable using New– Example: Dim MyEmp As New Emp

Page 14: Objects andVB Classes

Creating Property with Property Procedures

• Implementing a property with a public variable the property value cannot be validated by the class.

• We can create read-only, write-only, or write-once properties with property procedure.

• Steps:– Declaring a private class variable to hold the property

value.

– Writing a property procedure to provide the interface to the property value.

Page 15: Objects andVB Classes

Private pvEid As String Private pvEname As String Private pvSalary As Double Public Property eid() As String Get eid = pvEid End Get Set(ByVal Value As String) pvEid = Value End Set End Property Public Property eName() As String Get eName = pvEname End Get Set(ByVal Value As String) pvEname = Value End Set End Property Public Property Salary() As Double Get Salary = pvSalary End Get Set(ByVal Value As Double) pvSalary = Value End Set End Property

Page 16: Objects andVB Classes

Property Procedure Code Example

Public Class Emp2 Public SSN As String Public Ename As String Public DateHired As Date Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value < 1 Or Value > 4 Then hiddenJobCode = 1 Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get End Property

End Class

Page 17: Objects andVB Classes

How the Property Procedure Works?

• When the program sets the property, the property procedure is called and the code between the Set and End Set statements is executed. The value assigned to the property is passed in the Value argument and is assigned to the hidden private variable.

• When the program reads the property, the property procedure is called and the code between the Get and End Get statements is executed.

Page 18: Objects andVB Classes

Implementing a Read-Only Property

• Declare the property procedure as ReadOnly with only the Get block.

• Ex. Create a YearsEmployed property from the DateHired property:

Public ReadOnly Property YearsEmployed() As Long Get YearsEmployed = Now.Year - DateHired.Year End Get End Property

– Note: It is similar to a calculated field in database.

Page 19: Objects andVB Classes

Implementing a Write-Only Property

• Declare the property procedure as WriteOnly with only the Set block.

• Ex. Create a PassWord property:Private hiddenPassword as String

Public WriteOnly Property Password() As String

Set(ByVal Value As String)

hiddenPassword=Value

End Set

End Property

Page 20: Objects andVB Classes

Anatomy of a Class Module

Class Module

Public Variables & Property Procedures

Public Procedures & Functions

Exposed Part

Private Variables

Private Procedures & Functions

Hidden Part

•Private variables and procedures can be created for internal use.

Page 21: Objects andVB Classes

Overloading

A class may have more than one methods with the same name but a different argument list (with a different number of parameters or with parameters of different data type), different parameter signature.

Page 22: Objects andVB Classes

Method Overloading Using the Overloads Keyword

Public Overloads Function tax() As Double

tax = salary * 0.1

End Function

Public Overloads Function tax(ByVal sal As Double) As Double

tax = sal * 0.1

End Function

Page 23: Objects andVB Classes

Inheritance

• The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.

Page 24: Objects andVB Classes

Employee Super Class with Three SubClasses

All employee subtypes will have emp nbr, name, address, and date-hired

Each employee subtype will also have its own attributes

Page 25: Objects andVB Classes

Inheritance ExamplePublic Class Emp

Public Eid As String

Public Ename As String

Public salary As Double

Public Function tax() As Double

tax = salary * 0.1

End Function

End Class

Public Class secretary

Inherits Emp

Public WordsPerMinute As Integer

End Class

Page 26: Objects andVB Classes

Overriding

• If a method in a base class is not appropriate for a derived class, we can override the base class method by adding a one with the same name to the derived class.

Page 27: Objects andVB Classes

Overriding ToString Method

Public Class Emp Public SSN As String Public FirstName As String Public LastName As String Public BirthDate As Date Public Overrides Function ToString() As String toString = FirstName & " " & LastName & "'s birthday is " & BirthDate.ToString End FunctionEnd Class

Page 28: Objects andVB Classes

.Net Framework Class Library Structure

• Assembly:– Basic unit of deployment.

– Implemented as Dynamic Link Library, DLL.

– May contain many Namespace

• NameSpace:– Organize a group of related classes.

• Class

• Object Browser– Ex: System.Windows.Forms

Page 29: Objects andVB Classes

Referencing Assemblies and Classes

• Each project automatically references essential assemblies.– Project property/References– Or: Solution Explorer/Show All Files

• Add additional reference:– Project/Add Reference

Page 30: Objects andVB Classes

Constructors

• A constructor is a method that runs when a new instance of the class is created. In VB .Net the constructor method is always named Sub New.

Page 31: Objects andVB Classes

Constructor ExamplePublic Sub New()

Me.eid = ""

ename = ""

salary = 0.0

End Sub

Public Sub New(ByVal empId As String, ByVal empName As String, ByVal empSal As Double)

eid = empId

ename = empName

salary = empSal

End Sub

Note: Cannot use Overloads with the New.

Page 32: Objects andVB Classes

Constructor of the Sub Class

Public Sub New(ByVal empId As String, ByVal empName As String, ByVal empSal As Double, ByVal WPM As Integer) MyBase.New(empId, empName, empSal) WordsPerMinute = WPM End Sub Public Sub New()

End Sub

Page 33: Objects andVB Classes

Constructors and Read-Only Field

• A constructor procedure is the only place from inside a class where you can assign a value to read-only fields.– Public ReadOnly currentDate As Date

– Public Sub New()

– Me.eid = ""

– ename = ""

– salary = 0.0

– currentDate = Today

– End Sub

Page 34: Objects andVB Classes

Working with Many Objects with Collections

Page 35: Objects andVB Classes

.Net Collection Data Structures

• System.Collection– Array– ArrayList– HashTable– Others:SortedList, Stack, Queue

Page 36: Objects andVB Classes

ArrayList

• More flexible than array:– No need to declare the number of objects in a

collection.– Objects can be added, deleted at any position.– Object can be retrieved from a collection by a

key.– Can store any types of data and objects.

Page 37: Objects andVB Classes

ArrayList

• Define an arraylist:– Dim myArrayList As New ArrayList()

• Properties:Count, Item, etc.– To retrieve the first member:

• myArrayList.Item(0) 0-based index

• Methods:– Clear, Add, Insert, Remove, RemoveAt,

Contains, IndexOf, etc.

Page 38: Objects andVB Classes

ArrayList Demo

Dim testArrayList As New ArrayList()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim f2 As New Form2()

testArrayList.Add("David")

testArrayList.Add(20)

testArrayList.Add(Fruits)

testArrayList.Add(f2)

TextBox1.Text = testArrayList.Item(0)

TextBox2.Text = testArrayList.Item(1).ToString

TextBox3.Text = testArrayList.Item(2)(1)

TextBox4.Text = testArrayList.Item(3).Age

End Sub

Page 39: Objects andVB Classes

For Each Loop with ArrayList

Dim testArrayList As New ArrayList()

Dim f2 As New DataForm2()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

testArrayList.Add("David")

testArrayList.Add(20)

testArrayList.Add(Fruits)

testArrayList.Add(f2)

Dim myObj As Object

For Each myObj In testArrayList

MessageBox.Show(myObj.GetType.ToString)

Next

Page 40: Objects andVB Classes

Using ArrayList as a Parallel Array

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged MessageBox.Show(rateList.Item(ListBox1.SelectedIndex)) End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load rateList.Add(0.05) rateList.Add(0.06) rateList.Add(0.07) rateList.Add(0.08) rateList.Add(0.09) rateList.Add(0.1) End Sub

Example: Select an interest rate from listbox and return its value

Page 41: Objects andVB Classes

Data Binding with ArrayLists

• Arraylists can be used as data source for a control.

• Demo: ListBox DataSource property.– Dim myArrayList As New ArrayList()– myArrayList.Add("apple")– myArrayList.Add("banana")– myArrayList.Add("orange")– ListBox1.DataSource = myArrayList

Page 42: Objects andVB Classes

Use arraylist to store many employee objects

Page 43: Objects andVB Classes

Module

Module Module1 Public empArrayList As New ArrayListEnd Module

Page 44: Objects andVB Classes

Data Entry Form

Dim newEmp As New emp newEmp.eid = TextBox1.Text newEmp.eName = TextBox2.Text newEmp.Salary = CDbl(TextBox3.Text) empArrayList.Add(newEmp)

Page 45: Objects andVB Classes

Update Form

Page 46: Objects andVB Classes

Creating ListBox and Display Selected Employee Data

Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim obj As Object For Each obj In empArrayList ListBox1.Items.Add(obj.eid) Next End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = empArrayList.Item(ListBox1.SelectedIndex).ename TextBox2.Text = empArrayList.Item(ListBox1.SelectedIndex).Salary.ToString End Sub

Page 47: Objects andVB Classes

Update Employee DataPrivate Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click If box1Changed Then empArrayList.Item(ListBox1.SelectedIndex).ename = TextBox1.Text End If If box2Changed Then empArrayList.Item(ListBox1.SelectedIndex).salary = CDbl(TextBox2.Text) End If End Sub Dim box1Changed As Boolean = False Dim box2Changed As Boolean = False Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged box1Changed = True End Sub Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged box2Changed = True End Sub

Page 48: Objects andVB Classes

Binding DataGridView

Private Sub Form6_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load DataGridView1.DataSource = empArrayList End Sub