10/5/2008 Objectives Applied • Given the specifications for an application that uses classes with any of the members presented in this chapter, develop the application and its classes. Chapter 11 • Use class diagrams, the Class View window, and the Class Details window to review, delete, and start the members of the classes in a solution. solution How to create and d use classes l Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 1 Murach’s Visual Basic 2008, C11 Slide 2 © 2008, Mike Murach & Associates, Inc. The architecture of a three-layer application Objectives (continued) Knowledge • List and describe the three layers of a three-layered application. • Describe these members of a class: constructor, method, field, and property. Presentation layer Main Windows form class Other form classes Middle layer Business B i classes Other supportt Oth classes Database classes Database • Describe the concept of encapsulation. • Explain p how instantiation works. • Describe the concept of overloading a method. • Explain what a shared member is. • Describe the difference between a class and a structure. Database layer Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 3 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. The members of a Product class The members of a Product class (continued) Properties Constructors Code Description Price Method GetDisplayText(sep) Murach’s Visual Basic 2008, C11 Description A String type that contains a product code. A String type that contains a product description. A Decimal type that contains the product’s price. Description Returns a string that contains the code, description, and price in a displayable format. The sep parameter is a string that’s used to separate the elements. © 2008, Mike Murach & Associates, Inc. New() Slide 4 Description Creates a Product object with default values. New(code, description, price) Creates a Product object using the specified code, description, and price values. Slide 5 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 6 1 10/5/2008 Types of class members Types of class members (continued) Class member Description Property Represents a data value associated with an object instance. Method An operation that can be performed by an object. Constructor A special type of method that’s executed when an object is instantiated. Delegate A special type of object that that’ss used to wire an event to a method. Event A signal that notifies other objects that something noteworthy has occurred. Field A variable that’s declared at the class level. Constant A constant. Class member Description Default property A special type of property that is used by default if a property name isn’t specified. It must include a parameter, which is typically used to access individual items within a class that represents a collection of objects. Operator A special type of method that’s performed for a Visual Basic operator such as + or =. Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 7 Murach’s Visual Basic 2008, C11 Class and object concepts The Product class • An object is a self-contained unit that has properties, methods, and other members. Public Class Product © 2008, Mike Murach & Associates, Inc. Slide 8 Private m_Code As String Private m_Description As String Private m_Price As Decimal • A class contains the code that defines the members of an object. • An object is an instance of a class, and the process of creating an object is called instantiation. Public Sub New() • Encapsulation is one of the fundamental concepts of objectoriented pprogramming. g g It lets yyou control the data and operations p within a class that are exposed to other classes. End Sub Public Sub New(ByVal code As String, _ ByVal description As String, _ ByVal price As Decimal) Me.Code = code Me.Description = description Me.Price = price End Sub • The data of a class is typically encapsulated within a class using data hiding. In addition, the code that performs operations within the class is encapsulated so it can be changed without changing the way other classes use it. • Although a class can have many different types of members, most of the classes you create will have just properties, methods, and constructors. Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 9 The Product class (continued) Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 10 The Product class (continued) Public Property Code() As String Get Return m_Code End Get Set(ByVal value As String) m_Code = value End Set End Property Public Property Price() As Decimal Get Return m_Price End Get Set(ByVal value As Decimal) m_Price = value End Set End Property Public Property Description() As String Get Return m_Description End Get Set(ByVal value As String) m_Description = value End Set End Property Public Function GetDisplayText(ByVal sep As String) _ As String Dim text As String = Code & sep _ & FormatCurrency(Price) _ & sep & Description Return text End Function End Class Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 11 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 12 2 10/5/2008 Two Product objects that have been instantiated from the Product class product1 Code=CS08 Description= Murach’s C# 2008 Price=54.50 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Code that creates the two Product object instances Dim product1, product2 As Product product1 = New Product("CS08", "Murach's C# 2008", 54.5D) product2 = _ New Product("VB08", "Murach's Visual Basic 2008", 54.5D) product2 Code=VB08 Description=Murach’s Visual Basic 2008 Price=54.50 Another way to create the object instances product1 = New Product With {.Code = "CS08", _ .Description = "Murach's C# # 2008 2008", .Price = 54.5D} product2 = New Product With {.Code = "VB08", _ .Description = "Murach's Visual Basic 2008", _ .Price = 54.5D} Slide 13 Code that checks if an object variable refers to an object Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 14 The dialog box for adding a class Dim product As Product . . If Product IsNot Nothing Then... Code that disassociates an object from an object variable Dim product As Product product = New Product("VB08", _ "Murach's Visual Basic 2008", 54.5D) . . product = Nothing The starting code for the new class Public Class Product End Class Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 15 Examples of field declarations Private m_Quantity As Integer ' A private field Public Price As Decimal ' A public field Public ReadOnly Limit As Integer = 90 ' A public read-only field Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 16 A version of the Product class that uses public fields instead of properties Public Class Product Public Code As String Public Description As String Public Price As Decimal Public Sub New() End Sub Public Sub New(ByVal code As String, _ ByVal description As String, _ ByVal price As Decimal) Me.Code = code Me.Description = description Me.Price = price End Sub Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 17 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 18 3 10/5/2008 The Product class with public fields (continued) The syntax for coding a public property Public [ReadOnly|WriteOnly] Property PropertyName As type [Get [statements] {PropertyName = propertyvalue} | {Return propertyvalue} End Get] [Set(ByVal variableName As type) [statements] propertyvalue = newvalue End Set] End Property Public Function GetDisplayText(ByVal sep As String) _ As String Dim text As String = Code & sep _ & FormatCurrency(Price) _ & sep & Description Return text End Function End Class Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 19 A read/write property Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 20 A statement that sets a property value Public Property Code() As String Get Return m_Code End Get Set(ByVal value As String) m_Code = value End Set End Property product.Code = txtProductCode.Text A statement that gets a property value Dim code As String = product.Code A read-only yp property p y Public ReadOnly Property DiscountAmount() As Decimal Get m_DiscountAmount = Subtotal * DiscountPercent Return m_DiscountAmount End Get End Property Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 21 A method that accepts a parameter Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 22 Two statements that call the method Public Function GetDisplayText(ByVal sep As String) _ As String Dim text As String = Code & sep _ & FormatCurrency(Price) _ & sep & Description Return text End Function lblProduct.Text = product.GetDisplayText(vbTab) lblProduct.Text = product.GetDisplayText() How the IntelliSense feature lists overloaded methods An overloaded version of the method that doesn’t accept parameters Public Function GetDisplayText() As String Dim text As String = Code & ", " _ & FormatCurrency(Price) _ & ", " & Description Return text End Function Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 23 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 24 4 10/5/2008 A constructor with no parameters A constructor with one parameter Public Sub New(ByVal code As String) Dim p As Product = ProductDB.GetProduct(code) Me.Code = p.Code Me.Description = p.Description Me.Price = p.Price End Sub Public Sub New() End Sub A constructor with three parameters Public Sub New(ByVal code As String, _ ByVal description As String, _ ByVal price As Decimal) Me.Code = code Me Description = description Me.Description Me.Price = price End Sub Statements that call the constructors Dim product1 As New Product Dim product2 As New Product("VB08", _ "Murach's Visual Basic 2008", 54.5D) Dim product3 As New Product(txtCode.Text) Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 25 © 2008, Mike Murach & Associates, Inc. Slide 26 A class that contains shared members Default values for instance variables Data type All numeric types Boolean Char Date Object Murach’s Visual Basic 2008, C11 Public Class Validator Default value 0 (zero) False Null (binary 0) 01/01/01 00:00:00 Null reference Private Shared m_Title As String = "Entry Error" Public Shared Property Title() As String Get Return m_Title End Get Set(ByVal value As String) m_Title = value End Set End Property Public Shared Function IsPresent(ByVal textBox _ As TextBox) As Boolean If textBox.Text = "" Then MessageBox.Show(textBox.Tag.ToString _ & " is a required field.", Title) textBox.Select() Return False Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 27 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 28 The Product Maintenance form A class that contains shared members (cont.) Else Return True End If End Function End Class Code that uses shared members If Validator.IsPresent(txtCode) AndAlso _ Validator IsPresent(txtDescription) AndAlso _ Validator.IsPresent(txtDescription) Validator.IsPresent(txtPrice) Then isValidData = True Else isValidData = False End If Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. The New Product form Slide 29 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 30 5 10/5/2008 The Tag property settings for the text boxes on the New Product form The Product class Control txtCode txtDescription txtPrice Code Property Tag property setting Code Description Price Description Price Method GetDisplayText(sep) Constructor New() Description A String variable; contains a product code. A String variable; contains a description of the product. A Decimal variable; contains the product’s price. Description Returns a string with the code, description, and price separated by the sep string. Description Creates a Product object with default values. New(code, description, price) Creates a Product object using the specified values. Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 31 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. The ProductDB class The Validator class Method Description GetProducts() A shared method that returns a List() of Product objects from the Products file. SaveProducts(list) A shared method that writes the products in the specified List() of Product objects to the Products file. Property N t Note IsPresent(textBox) s ese t(te t o ) • You don’t need to know how the ProductDB class works. You just need to know about its methods so you can use them in your code. Title Shared method IsInt32(textBox) IsDecimal(textBox) Slide 32 Description A shared string; contains the text that’s displayed in the title bar of a dialog box for an error message. Returns a Boolean value that indicates whether… Data w wass eentered e ed into o thee text e box. bo . An Integer type was entered into the text box. A Decimal type was entered into the text box. IsWithinRange(textBox, min, max) The value entered into the text box is within the specified range. Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 33 Public Class frmProductMaint Private products As List(Of Product) Private Sub frmProductMaint_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load products = ProductDB.GetProducts Me.FillProductListBox() End Sub Private Sub FillProductListBox() lstProducts.Items.Clear() For Each p As Product In products lstProducts.Items.Add(p.GetDisplayText(vbTab)) Next End Sub © 2008, Mike Murach & Associates, Inc. © 2008, Mike Murach & Associates, Inc. Slide 34 The Product Maintenance form (continued) The code for the Product Maintenance form Murach’s Visual Basic 2008, C11 Murach’s Visual Basic 2008, C11 Slide 35 Private Sub btnAdd_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnAdd.Click Dim newProductForm As New frmNewProduct newProductForm.ShowDialog() If newProductForm.Product IsNot Nothing Then products.Add(newProductForm.Product) ProductDB.SaveProducts(products) Me.FillProductListBox() End If End Sub Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 36 6 10/5/2008 The Product Maintenance form (continued) The Product Maintenance form (continued) Private Sub btnDelete_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnDelete.Click Dim i As Integer = lstProducts.SelectedIndex If i <> -1 Then Dim product As Product = products(i) Dim message As String = _ "Are you sure you want to delete " _ & product.Description & "?" Dim button As DialogResult = _ MessageBox.Show(message, _ "Confirm Delete", MessageBoxButtons.YesNo) If button = DialogResult.Yes Then products.Remove(product) ProductDB.SaveProducts(products) Me.FillProductListBox() End If End If End Sub Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 37 Private Sub btnExit_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnExit.Click Me.Close() End Sub End Class Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 38 The New Product form (continued) The code for the New Product form Private Sub btnCancel_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnCancel.Click Me.Close() End Sub Public Class frmNewProduct Public Product As Product Private Sub btnSave_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnSave.Click If IsValidData() Then Product = New Product(txtCode.Text, _ txtDescription.Text, CDec(txtPrice.Text)) Me.Close() End If End Sub End Class Private Function IsValidData() As Boolean Return Validator.IsPresent(txtCode) AndAlso _ Validator.IsPresent(txtDescription) AndAlso _ Validator.IsPresent(txtPrice) AndAlso _ Validator.IsDecimal(txtPrice) End Function Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 39 The code for the Validator class Slide 40 Else Return True End If End Function Private Shared m_Title As String = "Entry Error" Public Shared Property Title() As String Get Return m_Title End Get Set(ByVal value As String) m_Title = value End Set End Property Public Shared Function IsDecimal( _ ByVal textBox As TextBox) As Boolean Try Convert.ToDecimal(textBox.Text) Return True Catch ex As FormatException MessageBox.Show(textBox.Tag.ToString _ & " must be a decimal value.", Title) textBox.Select(0, textBox.Text.Length) Return False End Try Public Shared Function IsPresent( _ ByVal textBox As TextBox) As Boolean If textBox.Text = "" Then MessageBox.Show(textBox.Tag.ToString _ & " is a required field.", Title) textBox.Select() Return False © 2008, Mike Murach & Associates, Inc. © 2008, Mike Murach & Associates, Inc. The Validator class (continued) Public Class Validator Murach’s Visual Basic 2008, C11 Murach’s Visual Basic 2008, C11 End Function End Class Slide 41 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 42 7 10/5/2008 The Class View window* for the Product Maintenance application A class diagram* that shows two of the classes in the project *Not available in Visual Basic 2008 Express Edition *Not available in Visual Basic 2008 Express Edition Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 43 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 44 A Product structure The basic syntax for creating a structure Public Structure StructureName member declarations End Structure Public Structure Product Public Code As String Public Description As String Public Price As Decimal Public Sub New(ByVal code As String, _ ByVal description As String, _ ByVal price As Decimal) Me.Code = code Me.Description = description Me.Price = price End Sub Public Function GetDisplayText( _ ByVal sep As String) As String Return Code & sep & FormatCurrency(Price) _ & sep & Description End Function End Structure Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 45 Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 46 Code that declares a variable as a structure type and assigns values to it Dim p As Product ' Create an instance of the Product structure. p.Code = "VB08" ' Assign values to each instance variable. p.Description = "Murach's Visual Basic 2008" p.Price = 54.5D Dim message As String = p.GetDisplayText(vbCrLf) ' Call a method. Code that uses the structure’s constructor Dim p As New Product("VB08", _ "Murach's Visual Basic 2008", 54.5D) Murach’s Visual Basic 2008, C11 © 2008, Mike Murach & Associates, Inc. Slide 47 8