Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods,...

31
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data

Transcript of Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods,...

Lecture Set 11

Creating and Using ClassesPart B – Class Features –

Constructors, Methods, Fields, Properties, Shared Data

Slide 2

Objectives

Describe these members of a class: constructor, method, field, and property

Explain how instantiation works Describe the concept of overloading a

method Explain what a shared member is

Slide 3

Common Class Elements (repeated)

Classes contain other elements: Procedures (methods) – functions and subs –

operations that can be performed by an object. Constructors – special type of method that’s executed

when an object is instantiated Data stores (including properties)

Other forms – objects of the form data type Numerous objects of types defined by other

classes Variables (of primitive types)

Events (and Event handlers -- not always tied to forms) – an event is a signal that notifies other objects that something noteworthy has occurred

Slide 4

Common Class Elements (continued - repeated)

User defined data types – structures, enumerations, complex structured types (arrays of structures, lists or arrays of objects, etc)

Delegate - A special type of object that’s used to wire an event to a method

Data Stores Property - Represents a data value associated with an

object instance Field - A variable that’s declared at the class level Constant - A constant associated with the class 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 =.

Slide 5

How Instantiation Works

The process of creating an object from a class is called instantiation

You can create many instances of a single class

A class defines a reference type The variable that is created for the object

of a class thus contains a reference to the memory location where the object is stored and not the object itself

When an object is instantiated the appropriate constructor is executed

Slide 6

Fields Fields are class variables that are global

to (accessible by) all of the executable components of a class Usually declared as private and are not

accessible outside the class May also be declared as public or

protected and may also be declared using the friend modifier

Slide 7

Fields (continued)

The desirable goal in using classes is to encapsulate and protect class data stores from external reference except through methods of the class

Declaring fields as public defeats the purpose of using classes

If accessing some class data stores from outside the class is considered cumbersome, we can access them through the use of properties, which simplifies the access mechanism we have to use while still protecting the data

Slide 8

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

Slide 9

A 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

Slide 10

Shared versus Instance Data

Class data can be instance data or shared data Shared data is declared with the Shared

keyword One copy exists no matter the number

of class instances One copy of instance data exists for each

class instance How are shared data useful?

Slide 11

A Note on Designing with Shared Data

NOTE: A shared function operates within the context of shared data – it can access any shared data in a class, but it cannot access instance members

How is the shared counter NextHuman used below?Public Class Human '*** instance members Private ID As Integer Public Function GetInfo() As String Return "Human #" & CStr(ID) End Function '*** shared members Private Shared NextHuman As Integer = 1 Public Shared Function GetNextHuman() As Human '*** factory method Dim temp As New Human() temp.ID = NextHuman NextHuman += 1 Return temp End Function End Class

Slide 12

The Product Class with Public Fields (continued)

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

Slide 13

Using Properties to Access Private Data

If we wish to provide more convenient access to the private or protected data of a class, we can do so through the use of public properties

Slide 14

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

Slide 15

Different Types of Properties

A read/write property Public Property Code() As String

Get Return m_Code End Get Set(ByVal value As String) m_Code = value End Set End Property

A read-only property Public ReadOnly Property DiscountAmount() As Decimal Get m_DiscountAmount = Subtotal * DiscountPercent Return m_DiscountAmount End Get End Property

Slide 16

Accessing Properties

A statement that sets a property value product.Code = txtProductCode.Text

A statement that gets a property value Dim code As String = product.Code

Slide 17

Methods

Classes contain subs and functions The public subs and functions are called

methods There also can be private subs and

functions I call these methods as well (although the

book does not seem to) Why might we want a private method?

Methods perform operations on the data stores (attributes) of a class

Slide 18

Method Signatures and Overloading

A method’s signature is defined by its name and its unique combination of parameters

Note that the return value is not involved – it is assumed to always be the same

We can write methods having the same name but different sets of parameters

This is known as overloading Overloading provides multiple ways of

invoking a given method

Slide 19

A method that accepts a parameter Public Function GetDisplayText(ByVal sep As String) _ As String Dim text As String = Code & sep _ & FormatCurrency(Price) _ & sep & Description Return text End Function

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

Methods and Overloading

Slide 20

Overloading and Intellisense

How does Intellisense handle overloaded functions (when it shows you the parameter list)Two statements that call the method

lblProduct.Text = product.GetDisplayText(vbTab)

lblProduct.Text = product.GetDisplayText()

How the IntelliSense feature lists overloaded methods

Slide 21

Constructors

By default, VB will provide you with a default constructor for each class you write When you use new to create a new object (an

instance of a class), the VB default constructor assigns default values to all instance variables of the new object

If this is not what you want, you can write your own constructor(s) by taking advantage of overloading

How does the compiler know which constructor is being referenced when you use New applied to a type (class) with multiple constructors

Slide 22

Overloading Constructors

A constructor with no parameters 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.Price = price End Sub

Slide 23

More on Constructors

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

Statements that call the constructors Dim product1 As New Product

Dim product2 As New Product("VB05", _ "Murach's Visual Basic 2005", 52.5D)

Dim product3 As New Product(txtCode.Text)

Slide 24Murach’s Visual Basic 2005, C11

© 2006, Mike Murach &

Associates, Inc.

Slide 24

Default Values for Instance Variables

Data type Default value

All numeric types 0 (zero)

Boolean False

Char Null (binary 0)

Date 01/01/01 00:00:00

Object Null reference

Slide 25Slide 25

A Class that Contains Shared Members (optional)

Public Class Validator 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

Slide 26

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(txtPrice) Then isValidData = True Else isValidData = False End If

Slide 27

Class Shared Members (optional)

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(txtPrice) Then isValidData = True Else isValidData = False End If

Slide 28

The Product Class (optional)

Property Description

Code A String variable; contains a product code.

Description A String variable; contains a description of the product.

Price A Decimal variable; contains the product’s price.

Method Description

GetDisplayText(sep) Returns a string with the code, description, and price separated by the sep string.

Constructor Description

New() Creates a Product object with default values. New(code, description, price)

Creates a Product object using the specified values.

Slide 29

The ProductDB Class (optional)

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.

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

Slide 30

The Validator Class (optional)

Property Description

Title A shared string; contains the text that’s displayed in the title bar of a dialog box for an error message.

Shared method Returns a Boolean value that indicates whether…

IsPresent(textBox) Data was entered into the text box.

IsInt32(textBox) An Integer type was entered into the text box.

IsDecimal(textBox) 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.

Slide 31

The Code for the Product Maintenance Form (optional)

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