Presentation is loading. Please wait.

Presentation is loading. Please wait.

VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)

Similar presentations


Presentation on theme: "VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)"— Presentation transcript:

1 VB.NET Classes ISYS 812

2 Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties) and behaviors (methods) of the object. For example, a Customer object is an abstract representation of a real customer. Encapsulation: –The combination of characteristics of an object along with its behavior. –Data hiding: Each object keeps its data and procedures hidden and exposes only those data elements and procedures that it wishes to allow outside world to see. –The implementation of a class – in other words, what goes on inside the class – is separate from the class’s interface.

3 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. –Inherited classes should always have an “is a” relationship with the base class. –Reusability Polymorphism: The concept of using a single name for different behaviors. –Overriding: A derived class with a method named the same as a method in the base class is said to override the method in the base class. Overriding allows an inherited class to take different actions from the identically named method in the base class. –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.

4 Object Relationship Model Object: A basic system element that contains data and processes. –Encapsulation –Data hiding (Public, Private) Relationship: –Specialization: IS-A relationship One-way: A programmer is an employee, but an employee is not necessarily a programmer. Inheritance, base classes and derived classes –Composition: HAS-A relationship Classes that are components of other classes. May not be used to relate an attribute to the class that it describes. It is incorrect to say that a CAR HAS-A vehicleID. A Car is composed of a body, an engine, etc.

5 Advantages of Object-Oriented Programming Reusable objects –A class can be used in multiple projects. –New classes can be created by inheritance. Building-block concept

6 Adding a Class to a Project Project/Add Window Form/Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in the General Declaration section Property procedures: Set / Get –Adding methods Private variables and procedures can be created for internal use.

7 Anatomy of a Class Module Class Module Public Variables & Property Procedures Public Procedures & Functions Exposed Part Private Variables Private Procedures & Functions Hidden Part

8 Class Example Public Eid As String Public Ename As String Public salary As Double Public Function tax() As Double tax = salary * 0.1 End Function

9 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.

10 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 4 Then hiddenJobCode = 1 Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get End Property End Class

11 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.

12 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.

13 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 How to create a write-once property?

14 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

15 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.

16 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.

17 Modeling 1:M Relation with Classes Object-Oriented systems allow multi-value attribute. Employee –EID –Ename –Dependents Department –DID –Dname –Employees

18 Using Collections Define a collection: –Ex. Private Customers as New Collection Methods: –ADD: Add object to a collection Dim Customer as New clsCustomer Customers.Add(Customer) Add an object with a key: –Customers.Add(Customer, Customer.CID) –Item: Retrieve an object from a collection with a position index (base 1) or with a key. Customer = Customers.Item(1) Customer = Customer.Item(“C101”) –Count: Return the number of objects in a collection. –Remove: Delete an object with a position index or key.

19 Iterating Through a Collection Dim Customer as clsCustomer Dim Indx as Integer For Indx = 1 to Customers.Count ‘***Note: Base 1 index set Customer = Customers.Item(Indx) … class operations … Next Indx For Each Customer In Customers class operations Next Customer

20 Implementing a 1:M Relationship With Collection Public did As String Public dname As String Public emps As New Collection () Public eid As String Public ename As String Public salary As Double Class Department Class Employee

21 To Add a New Emp Dim department As New Dept() Private Sub DeptForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load department.did = "D1" department.dname = "MIS" TextBox1.Text = department.did TextBox2.Text = department.dname End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim newemp As New Emp() With newemp.Eid = TextBox3.Text.Ename = TextBox4.Text.salary = Val(TextBox5.Text) End With TextBox3.Text = vbNullString TextBox4.Text = vbNullString TextBox5.Text = vbNullString department.emps.Add(newemp) End Sub

22 To Find Total Salary and Number of Employees Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim temp As Emp Dim totalsal As Double totalsal = 0 For Each temp In department.emps totalsal = totalsal + temp.salary Next temp TextBox7.Text = totalsal.ToString End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click TextBox6.Text = department.emps.Count.ToString End Sub

23 Database Access with Classes

24 Single-Record-Handling Classes –Retrieves a single record from the database and makes it available to your application in the form of an object. –The fields in the record are exposed as the object’s properties. –Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.

25 Single-Record-Handling Class Example Imports System.Data.OleDb Public Class Customer Public cid As String Public CName As String Public City As String Public Rating As String Private hiddenexist As Boolean Private cn As OleDb.OleDbConnection Public ReadOnly Property RecExist() Get RecExist = hiddenexist End Get End Property

26 Public Sub getData(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read() = False Then hiddenexist = False MsgBox("Record does not exist") ‘Better let user’s program to display msg Else hiddenexist = True cid = objDataReader("cid") CName = objDataReader("CName") City = objDataReader("City") Rating = objDataReader("Rating") End If objConn.Close() End Sub

27 Public Sub SaveNew() Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) objConn.Open() Dim strSQLInsert As String strSQLInsert = "Insert into Customer values ('" strSQLInsert = strSQLInsert & cid & "','" & CName & "','" strSQLInsert = strSQLInsert & City & "','" & Rating & "')" Dim objCommInsert As New OleDbCommand(strSQLInsert, objConn) objCommInsert.ExecuteNonQuery() objConn.Close() End Sub

28 Using the SaveNew Method to Add A New Customer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim newCust As New Customer() newCust.cid = TextBox1.Text newCust.CName = TextBox2.Text newCust.City = TextBox3.Text newCust.Rating = TextBox4.Text newCust.SaveNew() TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox4.Text = "" End Sub

29 Classes That Create Oledb Objects Example: Create a class that uses methods to return DataReader.

30 Imports System.Data.OleDb Public Class ReaderServer Public Function CustReader() As OleDbDataReader Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() CustReader = objComm.ExecuteReader() End Function Public Function OrderReader() As OleDbDataReader Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from orders;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() OrderReader = objComm.ExecuteReader() End Function End Class

31 Using the Class Dim cReader As New ReaderServer() Private Sub UseReader_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim reader As OleDb.OleDbDataReader reader = cReader.CustReader() Do While reader.Read() = True ListBox1.Items.Add(reader("cid")) Loop End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Dim reader As OleDb.OleDbDataReader reader = cReader.OrderReader Dim strResult As String Do While reader.Read() = True If reader("cid") = ListBox1.SelectedItem Then strResult = strResult + reader("oid") + " " + reader("odate") + vbCrLf End If Loop TextBox1.Text = strResult End Sub

32 Importing Data From Database to Class Example: Customer/Order class: Public Class CustOrders –Public cid As String –Public CName As String –Public City As String –Public Rating As String –Public orders As New Collection() –Public Sub getData(ByVal SearchID As String) Public Class Order – Public OID As String – Public Odate As Date – Public SalesPerson As String –End Class Demo: VBClass/CustOrdForm.vb

33 Public Sub getOrders(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from orders where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True Dim ord As New Order() ord.OID = objDataReader("oid") ord.Odate = objDataReader("odate") ord.SalesPerson = objDataReader("salesPerson") orders.Add(ord) Loop If orders.Count = 0 Then MessageBox.Show("customer has no order") End If objConn.Close() End Sub

34 Namespaces Namespaces provide a mechanism for organizing classes and for preventing conflicts between classes of the same name. The default namespace for any class is the name of the project.

35 Assemblies An assembly is a logical grouping of functionality into a physical file. One or many business logic components can be reside in an assembly. This collection of components is compiled into a.DLL file. We can import this.DLL component to any VB projects.

36 Steps to Create An Assembly Create a class library with classes. –You can also use existing classes by Project/Add Existing Item Select Build/Build Solution to compile the code. –When the class library is compiled successfully, an assembly is created and stored in the project’s Bin folder. Note: A ClassLibrary project does not reference System.Windows.Forms namespace.

37 Using the Assembly Reference the assembly: Project/Add Reference and use the Browse button to select the assembly. Import the assembly.

38 Code Using Assembly Imports MyAssembly Public Class UseAssembly Inherits System.Windows.Forms.Form Dim testAssembly As New MyAssembly.Customer() Private Sub UseAssembly_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load testAssembly.cid = "1" testAssembly.getData(testAssembly.cid) TextBox1.Text = testAssembly.CName TextBox2.Text = testAssembly.Rating End Sub End Class


Download ppt "VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)"

Similar presentations


Ads by Google