Creating Reusable Components with Classes - PowerPoint PPT Presentation

1 / 51
About This Presentation
Title:

Creating Reusable Components with Classes

Description:

Programming with Visual Basic .NET. An Object-Oriented Approach. Chapter 12 ... Programming with Visual Basic .NET. An Object-Oriented Approach. Slide 3. The ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 52
Provided by: michaelv82
Category:

less

Transcript and Presenter's Notes

Title: Creating Reusable Components with Classes


1
Chapter 12
  • Creating Reusable Components with Classes

2
Objectives
  • Understand the concept of a component
  • Understand the role of author and developer in
    creating and testing components
  • Define a namespace
  • Create events in a class module
  • Understand the types of class data
  • Create properties with Public variables and
    Property Procedures
  • Create enumerations
  • Create methods
  • Learn about overloading

3
The Theory of Component Creation
  • Remember that VB .NET is an object-oriented
    programming language
  • Data and the processes that act on that data are
    encapsulated into classes supporting properties,
    methods, and events
  • The encapsulated package is called a component
  • The interface for a component is the properties,
    methods, and events supported by the component
  • The implementation is that part of the component
    hidden from the developer

4
The Role of Author and Developer
  • The author creates components intended for reuse
    by other developers
  • The author creates the Class Library project
  • The developer uses components created by an
    author
  • The developer uses the Class Library project in a
    Windows Application project
  • When developing and testing components, you
    switch back and forth between the roles of author
    and developer

5
Introduction to Component Creation
  • Create a solution file with two project files
  • One project file is a Class Library project
  • Class Library project contains the components
  • Second project is a typical Windows Application
    project
  • Windows Application project is used to test the
    Class Library project

6
Relationship between the Solution File and its
Project Files
Solution file Complete12.sln
Project file Complete12.vbproj
Project file Complete12Library.vbproj
compile
compile
Executable file run by user Complete12.exe
Library referenced by developer Complete12Library.
dll
7
Creating a Component
  • Create a Class Library project by adding a new
    project to an existing solution
  • Project is created from a template using the Add
    New Project dialog box
  • Specify Class Library as the template

8
Add New Project Dialog Box
Specify Class Library template
Project name
9
Solution Explorerwith Two Projects
Solution
Windows Application project
Class Library project
10
Defining the Namespace for a Component
  • Remember that all classes are organized into
    namespaces
  • When you created a desktop application, VB .NET
    defined a default name for you
  • By default, the Namespace name is the same as the
    project name
  • Namespaces are organized into a hierarchy
  • System is a root namespace because it appears at
    the top of the hierarchy
  • System.Windows.Forms belongs to the System
    namespace

11
Naming Rules for Namespaces
  • Microsoft recommends that namespace names be
    defined as follows
  • CompanyName.TechnologyName
  • CompanyName contains the name of the company who
    developed the namespace
  • TechnlogyName contains a particular technology
  • For Example
  • Course.TrafficSignals

12
Defining the Root Namespace
Output file name
Type of file produced
Output file name
13
Referencing Namespaces between Projects (Steps)
  • Select the Windows Application project in the
    Solution Explorer
  • Click Project, and then click Add Reference to
    display the Add Reference dialog box
  • Click the Projects tab
  • Select the Class Library project, and then click
    OK to add it

14
Add Reference Dialog box
Available project(s)
Selected project(s)
15
Understanding the Imports Statement
  • The Imports statement does not make a namespace
    available for use
  • Its purpose is to allow you to reference the
    classes in a namespace without using a fully
    qualified reference
  • Multiple Imports statements can appear to import
    multiple namespaces
  • Imports statements typically appear after the
    Option Explicit and Option Strict statements

16
Namespace Hierarchies
  • Namespaces are organized hierarchically
  • You can create your own namespace hierarchies

17
Namespace Hierarchy (Illustration)
Root namespace Course
Technology TrafficSignals
Other technologies
Class StopLight
Class LeftHandTurn
Other classes
18
Declaring a Namespace
  • Namespace statement forms a block and contains
    one or more classes
  • End Namespace statement marks the end of the
    namespace
  • Namespaces, in turn, contains classes

Namespace TrafficSignals Class StopLight
' Statements End Class Class
LeftHandTurn ' Statements End
Class End Namespace
19
Class Events (Introduction)
  • As the developer, you have written event handlers
    throughout this book
  • Windows raised events as the user interacted with
    the form or control instances on the form
  • As the author you must define events and raise
    them to the developer
  • Event statement declares an event
  • RaiseEvent statement raises an event
  • Note that we use the terms "raising an event" and
    "firing an event" synonymously

20
Class Events (Syntax)
  • Public Event procedurename (arglist )
  • Optional Public keyword indicates that the event
    has Public access (visibility)
  • Event keyword declares an event
  • Note that it does not fire the event
  • Procedurename defines the name of the event
  • Standard variable and procedure naming rules
    apply
  • Optional arglist contains arguments passed to the
    event
  • Arguments can be passed by value or by reference

21
Declaring an Event (Example)
  • Declare an event named LightChange
  • Public Event LightChange(ByVal _ CurrentLight As
    Color)
  • Event is named LightChange
  • Event takes one argument having a data type of
    color

22
Raising an Event
  • RaiseEvent statement fires an event
  • Syntax
  • RaiseEvent eventname ( arglist )
  • RaiseEvent statement appears in a procedure and
    will fire an event
  • eventname contains the event to fire
  • Declare the event with the Event statement
  • arglist contains zero or more arguments
  • Arguments must match event declaration

23
Declaring and Raising Events
Class Library project (author) Declare the
event Raise the event
Public LightChange(ByVal currentLight As Color)
Private Sub tmrLight_Tick( . . .) Handles
tmrLight_Tick RaiseEvent(mLight) End Sub
Windows Application project (developer)
Private Sub LightNorth_LightChange( _ ByVal
currentLight As StopLight.Color) Handles _
LightNorth.LightChange ' Statement in event
handler. End Sub
24
Creating a Class Instance (1)
  • Use the same syntax as you would use to create
    any other class instance
  • Use the New keyword to create a class instance
  • Omit the New keyword to just declare an object
    variable that references Nothing

25
Creating a Class Instance (2)
  • Create an instance of the StopLight class
  • Private LightNorth As New StopLight()
  • Create an instance of the StopLight class using
    two statements
  • Private LightNorth As StopLightLightNorth New
    StopLight()

26
Types of Class Data
  • Data can be exposed or hidden from the developer
  • Hidden data is not available to the developer and
    is part of the classs implementation
  • Exposed data is available to the developer and is
    part of the interface
  • Define hidden or exposed data using the same
    declaration statements that you have used in the
    past
  • Public, Private, Friend, Dim

27
Declaring Class Data
  • Public variables are exposed (part of the
    interface) and are considered properties
  • Friend variables are shared by the classes in a
    project but not outside the project
  • Private variables are hidden in the class
    containing the declaration so they are part of
    the implementation
  • Local variables appear in a procedure and are
    part of the implementation
  • Declare local variables with the Dim keyword

28
Creating a First Property
  • The easiest way to create a property is to
    declare a Public variable in a class
  • Create property names such that they contain full
    words
  • Capitalize the first letter of each word
  • Avoid obscure abbreviations
  • Example to declare a property named Location
    having a data type of String
  • Note that the declaration appears in the class
    module
  • Public Class StopLight
  • Public Location As String
  • End Class

29
Referencing a Property
  • Use the same object.property syntax with which
    you are familiar
  • Note that the Intellisense technology works too
  • Example
  • Private LightNorth As New StopLight()
  • LightNorth.Location "Northbound Main Street"

30
Introduction to Enumerations
  • You have been using predefined enumerations
    throughout this book
  • Message box icons
  • Colors
  • Etc.
  • You can create your own enumerations with the
    Enum statement
  • A class can have multiple enumerations

31
Enum Statement (Syntax 1)
  • Public Private Friend Enum name
  • membername constantexpression
  • membername constantexpression
  • . . .
  • End Enum

32
Enum Statement (Syntax 2)
  • Public, Private, and Friend keywords define the
    scope of the enumeration
  • Meaning is the same as with other variable
    declarations
  • Enum statement marks the beginning of the
    enumeration block
  • name contains the name of the enumeration
  • membername is an element of the enumeration
  • An enumeration can contain as many elements as
    needed
  • constantexpression contains the value of the
    enumeration member
  • By default numbering is sequential starting at 0
  • End Enum statement marks the end of the
    enumeration

33
Enumeration (Example 1)
  • Declare an enumeration named Color with 4
    members
  • Public Enum Color
  • Green 1
  • Yellow 2
  • Red 3
  • None 4
  • End Enum

34
Enumeration (Example 2)
  • Enumerations need not have unique or sequential
    values
  • Example to declare an enumeration for the number
    of days in a particular month

Public Enum DaysInMonth January 31
February 28 March 31 April 30
May 31 . . . December 31 End Enum
35
Creating Enumerated Variables
  • After declaring an enumeration, you can declare
    variables having an enumerated type
  • Example
  • Public CurrentColor As Color
  • Store a value in the enumeration
  • CurrentColor Color.Green

36
Hiding Data in a Class
  • Simply declare a Private constant or Private
    variable in a class
  • Local variables declared in a procedure are also
    hidden
  • Static local variables declared in a procedure
    are also hidden

37
Creating Procedures in a Class
  • Function and Sub procedures in a class module
    have the same syntax as Function and Sub
    procedures declared anywhere else
  • Private procedures are hidden and are part of the
    implementation
  • Public procedures are exposed and are part of the
    interface
  • Procedures can also be declared as Friend

38
Creating a Method
  • Create a Public Function procedure to create a
    method that returns a value
  • Create a Public Sub procedure to create a method
    that does not return a value
  • Both Function and Sub procedures can accept 0 or
    more arguments
  • Naming conventions
  • Use a verb in the procedure name to denote a
    method
  • Use whole words avoiding obscure abbreviations

39
Property Procedures (Introduction)
  • Property Procedures provide an alternative to
    creating properties with Public variables
  • Code executes when the developer reads or writes
    a property created with a Property Procedure
  • Thus, the data can be validated
  • In addition, code can be written to store and
    retrieve values from other variables

40
Property Procedures (Syntax 1)
  • Default ReadOnly WriteOnly Property
    varname ( parameter list ) As type
  • Get
  • block
  • End Get
  • Set ( ByVal value As typename )
  • block
  • End Set
  • End Property

41
Property Procedures (Syntax 2)
  • Default keyword means that the property is
    read-write. It can be omitted
  • Both Get and Set blocks must exist
  • ReadOnly keyword indicates that property is
    read-only
  • Get block must exist
  • Set block must not exist
  • WriteOnly keyword indicates that property is
    write-only
  • Get block must not exist
  • Set block must exist

42
Property Procedures(Syntax 3)
  • varname contains property name
  • Standard variable naming rules apply
  • parameter list argument defines arguments used to
    set the property
  • As type clause defines the data type of the
    property
  • Required because we use Option Explicit in this
    book
  • Code in the Get block executes when the developer
    reads the property's value
  • Code in the Set block executes when the developer
    writes the property's value

43
Creating a Read-Write Property
  • Example
  • Public Property GreenInterval() As Integer
  • Get
  • Return mintGreenInterval
  • End Get
  • Set (ByVal Value As Integer)
  • mintGreenInterval Value
  • Call ResetTimer(mOperationMode, mLight)
  • End Set
  • End Property

44
Property Procedures (Illustration)
Write property LightNorth.GreenInterval 2000
Read property pintInterval LightNorth.GreenInte
rval
Public Property GreenInterval() As Integer
Get Return mintGreenInterval End
Get Set (ByVal Value As Integer)
mintGreenInterval Value Call
ResetTimer(mOperationMode,mLight) End
Set End Property
Execute Get block
Execute Set block
45
Creating a Read-Only Property (Example)
  • Include the ReadOnly keyword
  • Omit the Set block
  • Public ReadOnly Property CurrentColor() As Color
  • Get
  • Return mLight
  • End Get
  • End Property

46
Creating a Write-Only Property (Example)
  • Include the WriteOnly keyword
  • Omit the Get block
  • Private WriteOnly Property SetCurrentColor() _
  • As Color
  • Set (ByValue Value As Color)
  • mLight Value
  • End Set
  • End Property

47
Creating a Write-Once Property
  • Use the same syntax as you would use to create a
    read-write property but
  • Declare a Static Boolean variable in the Set
    block
  • Set the value to True when the property is set
    the first time
  • Use an If statement to test whether the property
    has been set previously and throw an exception if
    necessary

48
Creating a Write-Once Property (Example)
Public Property ID() As Integer Get
Return mintID End Get Set (ByVal Value As
Integer) Static pblnSet As Boolean
If pblnSet True Then Throw New
System.Exception() Else
pblnSet True mintID Value
End If End Set End Property
49
Parameterized Properties
  • Parameterized properties accept multiple
    arguments
  • Example using a hidden array

Private msngList(100) As Single Public Property
Item(ByVal pintArg As Integer) As Single Get
Return msngList(pintArg) End Get
Set (ByVal Value As Integer)
msngList(pintArg) Value End Set End
Property
50
Overloading
  • Overloading refers to the ability to create
    multiple procedures having the same name but
    varying argument lists
  • Methods can have a different number of arguments
  • Methods can have arguments having different data
    types
  • Use the Overloads keyword to overload a method

51
Overloading (Illustration)
LightNorth.SetOperationMode() LightEast.SetOperat
ionMode(Stoplight.Color.Red) LightNorth.SetOperat
ionMode(StopLight.OperationMode.CycleFlash) Light
East.SetOperationMode(StopLight.OperationMode.Cycl
eflash,StopLight.Color.None)
Write a Comment
User Comments (0)
About PowerShow.com