480 likes | 577 Views
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.
E N D
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. • 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.
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.
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
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
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
Procedures . Sub procedure: Sub SubName(Arguments) … End Sub • To call a sub procedure SUB1 • CALL SUB1(Argument1, Argument2, …)
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.
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
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
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
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
Using a Class • Define a class variable using New • Example: Dim MyEmp As New Emp
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.
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
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
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.
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.
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
Anatomy of a Class Module Class Module Exposed Part Hidden Part Public Variables & Property Procedures Private Variables Public Procedures & Functions Private Procedures & Functions • Private variables and procedures can be created for internal use.
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.
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
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.
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
Inheritance Example Public 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
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.
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 Function End Class
.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
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
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.
Constructor Example Public 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.
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
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
.Net Collection Data Structures • System.Collection • Array • ArrayList • HashTable • Others:SortedList, Stack, Queue
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.
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.
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
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
Using ArrayList as a Parallel Array Example: Select an interest rate from listbox and return its value 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
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
Module Module Module1 Public empArrayList As New ArrayList End Module
Data Entry Form Dim newEmp As New emp newEmp.eid = TextBox1.Text newEmp.eName = TextBox2.Text newEmp.Salary = CDbl(TextBox3.Text) empArrayList.Add(newEmp)
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
Update Employee Data Private 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
Binding DataGridView Private Sub Form6_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load DataGridView1.DataSource = empArrayList End Sub