Chapter 6 OOP: Creating ObjectOriented Programs - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

Chapter 6 OOP: Creating ObjectOriented Programs

Description:

Ayati's Notes Programming In Visual Basic.NET by Julia Case Bradley & Anita C. Millspaugh ... Basic.NET. 6 2. Ayati's Notes Programming In Visual Basic.NET ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 53
Provided by: richard542
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6 OOP: Creating ObjectOriented Programs


1
Chapter 6OOP Creating Object-Oriented Programs
  • Programming In
  • Visual Basic.NET

2
Object Terminology Review
  • Object - like a noun, a thing
  • Buttons, Text Boxes, Labels
  • Properties - like an adjective, characteristics
    of object
  • Text, ForeColor, Checked, Visible, Enabled
  • Methods - like a verb, an action or behavior,
    something the object can do or have done to it
  • ShowDialog, Focus, Clear, ToUpper, ToLower
  • Events - object response to user action or other
    events
  • Click, Enter, Activate

3
Thus Far . . .
  • Since Chapter 1 we have been using objects
  • Up until now the classes for all objects used
    have been predefined
  • We have created new objects for these classes by
    using the controls in the Toolbox
  • VB allows programmers to create their own object
    types by creating a Class Module

4
Class and Instance
  • When we add a button object from the button tool
    in the toolbox to the form we are creating an
    Instance of the Button Class
  • The button object is an Instance of the Button
    Class
  • Every button on the form is an Instance
  • Defining your own Class is like creating a new
    tool for the Toolbox

5
"Cookie Analogy"
  • Class Cookie cutter
  • Instantiate Making a cookie using the cookie
    cutter
  • Instance Newly made cookie
  • Properties of the Instance may have different
    values
  • Icing property can be True or False
  • Flavor property could be Lemon or Chocolate

6
"Cookie Analogy" (cont.)
  • Methods Eat, Bake, or Crumble
  • Events Cookie crumbling all by itself and
    informing you

Methods and Events are often difficult to
distinguish!
7
Encapsulation Hiding
  • Combination of characteristics of an object along
    with its behavior in "one package"
  • Cannot make object do anything it doesn't already
    "know" how to do
  • Cannot make up new properties, methods, or events
  • Sometimes referred to as data hiding an object
    can expose only those data elements and
    procedures that it wishes

8
Inheritance
  • Ability to create a new class from an existing
    class
  • Purpose of Inheritance is reusability
  • For example, each form created is inherited from
    the existing Form class
  • Original class is called
  • Base Class, Superclass, or Parent Class
  • Inherited class is called
  • Subclass, Derived Class, or Child Class

9
Inheritance (cont.)
  • Examine 1st line of code for a form in the Editor

Inherited Class, Derived Class Subclass, Child
Class
Public Class Form1 Inherits System.Windows.Forms.
Form
Base Class, Super-class, Parent Class
10
Inheritance Example
  • Base Class
  • Person
  • Subclasses
  • Employee
  • Customer
  • Student

11
Polymorphism
  • Different classes of objects may have behaviors
    that are named the same but are implemented
    differently
  • Programmers can request an action without knowing
    exactly what kind of object they have or exactly
    how it will carry out the action

12
Polymorphism Implemented
  • Overloading
  • Argument type determines which version of a
    method is used
  • Example MessageBox.Show method
  • Overriding
  • Refers to a class that has the same method name
    as its base class
  • Method in subclass takes precedence

13
Reusability
  • The main purpose behind OOP and Inheritance in
    particular
  • New classes created with Class Module can be used
    in multiple projects
  • Each object created from the class can have its
    own properties

14
Multi-tier Applications What is it?Three-tier
Model
  • Most common implementation of multi-tier

Data Tier
Presentation Tier User Interface Forms Controls
Menus
Business Tier (Processes in codes) Business
Objects Validation Calculations Business
Logic Business Rates
15
Multi-tier Applications
  • Common use of classes is to create multi-tier
    applications
  • Each of the functions of a multi-tier application
    can be coded in a separate component and stored
    and run on different machines
  • Goal is to create components that can be combined
    and replaced

16
Instantiating An Object
  • Creating a new object based on a class
  • Create an instance of the class by using the New
    keyword and specify the class
  • General Form

New className ( )
Dim fntMyFont New Font ("Arial",
12) lblMsg.Font fntMyFont OR lblMsg.Font
New Font ("Arial", 12)
17
Specifying a Namespace
  • In your projects, you have noticed the Inherits
    clause when VB creates a new form class

Name of the Class
Public Class Form1 Inherits System.Windows.Forms.
Form
Namespace
18
Namespace
  • Entire namespace is not needed for any classes in
    the namespaces that are automatically included in
    a Windows Forms project which include
  • System
  • System.Windows.Forms
  • System.Drawing
  • When referring to classes in a different
    namespace
  • Write out the entire namespace
  • Add and Imports Statement to include the namespace

19
Class Design - Analyze
  • Characteristics of your new objects
  • Characteristics will be properties
  • Define the properties as variables in the class
    module
  • Behaviors of your new objects
  • Behaviors will be methods
  • Define the methods as sub procedures and
    functions in the class module

20
Create a New Class
  • Project, Add Class Module
  • Add New Item dialog, choose Class
  • Name the Class

1
2
  • Next
  • Define the Class properties
  • Code the methods

3
21
Create a New Class 4. Define the Class
properties
  • Project, Add Class Module
  • Add New Item dialog, choose Class
  • Name the Class

22
Create a New Class 5. Code the methods
Property Quantity() As Integer Get
Quantity mQty End Get
Set(ByVal Value As Integer) mQty
Value End Set End Property
'BookSale Classto handle boosale
information 'Folder PracticeCH_1 Public Class
BookSale Private mTitle As String Private
mQty As Integer Private mPrice As Decimal
3-2
1
2
Property Price() As Decimal Get
mPrice Price End Get Set(ByVal Value As
Decimal) Price Value End
Set End Property
3-3
Property Title() As String Get
Title mTitle End Get
Set(ByVal Value As String) mTitle
Value End Set End Property
3-1
Public Function ExtPrice() As Decimal
Return mQty mPrice End Function End Class
4
Back
1
23
Properties of a Class
  • Define variables inside the Class Module by
    declaring them as Private
  • Do not make Public. That would violate
    Encapsulation (each object should be in charge of
    its own data)
  • Private mintPatientNum as Integer
  • Private mdtmDate as Date
  • Private mstrLastName as String

24
Assign Values to Properties
  • Write special property procedures to
  • Pass the values to the class module
  • Return values from the class module
  • Name used for property procedure is the name of
    the property seen by the outside world
  • Property Get
  • Retrieves property values from a class
  • Like a function must return a value
  • Property Set
  • Sets or assigns values to properties

25
Property Procedure General Form
Private ClassVariable As DataType Public
Property PropertyName As DataType Get PropertyN
ame ClassVariable End Get Set (ByVal Value
As DataType) statements, such as
validation ClassVariable Value End Set End
Property
26
Read-Only Properties
  • In some instances a value for a property should
    only be retrieved by an object and not changed
  • Create a read-only property by using the ReadOnly
    modifier
  • Write only a Get portion of the property procedure

Public ReadOnly Property PropertyName As
DataType
27
Code a Method
  • Create methods by adding sub procedures and
    functions for the behaviors to the class module
  • The sub procedures and functions should be
    defined as Public

28
Create Regions
  • Regions of code allow sections of code to be
    hidden in the same way that the Editor hides
    Windows generated code
  • To add a region
  • Include Region Statement followed by a string
    literal giving the region's name
  • End Region tag will be added automatically
  • Write code between the 2 statements

29
Creating a New Object Using a Class
  • Similar to creating a new tool for the toolbox
    but not yet instantiating
  • Declare a variable for the new object with
    datatype of the class
  • Private mBookSale As BookSale
  • Then, instantiate the object using the New
    keyword
  • mBookSale New BookSale
  • Dim mBookSale As New BookSale ltlt
  • Alternatively Dim mBookSale As BookSale New
    BookSale
  • mBookSale New BookSale(txtTitle.Text, _
  • CInt(txtQuantity.Text), _
  • CDec(txtPrice.Text))

30
Best Practices
  • You may declare and instantiate an object at the
    same time but this is not best practice
  • Should declare the variable separately in the
    Declarations section
  • Instantiate the object
  • Only when(if) it is needed
  • Inside a Try/Catch block for error handling
    (Try/Catch block must be inside a procedure)

31
Inheriting Form Classes
  • Many projects require several forms
  • Create a base form and inherit the visual
    interface to new forms
  • Base form inherits from System.Windows.Forms.Form
  • Subclass from inherits from Base form

32
When you change the name of the from object, in
the projects Property Page the startup object
does not automatically change to the new name of
the form until you click on it in the drop-down
list then the old name disappears. Press Apply
button, then press OK.
See the output message
33
Creating Inherited Form Class
  • Project menu, Add Windows Form
  • Modify the Inherits Statement to inherit from
    bass form using project name as the namespace
  • OR
  • Project menu, Add Inherited Form
  • In dialog select name of Base form

34
Creating Inherited Form Class, Cont
Then Build Solution
Then Build or ReBuild
35
Creating Inherited Form Class, Cont
Add any object (e.g. btn OK) to the form, then
Build (or ReBulid), the inherited object will
apear on the inherited from with a special sign.
36
Creating Inherited Form Class, Cont
When the program runs, the user will not see the
inheritance symbols
37
Creating Inherited Form Class, Cont
'This program is to Calculate Ext. Price using
BookSale Class Public Class frmSales Inherits
InheritApp_1.frmBase Page 253 Region " Windows
Form Designer generated code " End Region
Private mBookSale As BookSale Private Sub
btnCalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles
btnCalc.Click Try mBookSale
New BookSale mBookSale.Price
CDec(txtPrice.Text)
mBookSale.Quantity CDec(txtQty.Text)
mBookSale.Title txtTitle.Text
lblExtPrice.Text FormatNumber(mBookSale.Extended
Price) Catch
MessageBox.Show("Quantity Price must be Numeric
and gt0", _ "Input
Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation) End Try
End Sub End Class
Option Strict On Public Class BookSale Region
"Properties" Private mstrTitle As String
Private mintQuantity As Integer Private
mdecPrice As Decimal Property Title() As
String Get Title mstrTitle
End Get Set(ByVal Value As
String) mstrTitle Value End
Set End Property Property Quantity() As
Integer Get Quantity
mintQuantity End Get Set(ByVal
Value As Integer) If Value gt 0 Then
mintQuantity Value
End If End Set End Property
Property Price() As Decimal Get
Price mdecPrice End Get
Set(ByVal Value As Decimal) If Value
gt 0 Then mdecPrice Value
End If End Set End
Property End Region Region "Methods"
Public Function ExtendedPrice() As Decimal
'Calculate the extended price Return
mintQuantity mdecPrice End Function End
Region End Class
Run Step-by-Step, F11
38
Instance versus Shared Variables
  • Instance variables or properties
  • Separate memory location for each instance of the
    object
  • Shared variables or properties (Use the Shared
    keyword to create)
  • Single memory location that is available for ALL
    objects of a class
  • Can be accessed without instantiating an object
    of the class
  • Shared mdecDiscountTotal As Decimal
  • Protected Shared mdecSalesTotal As Decimal
  • Protected Shared mintSalesCount As Integer
  • Shared Methods can also be created
  • Shared ReadOnly Property DiscountTotal() As
    Decimal
  • Get
  • DiscountTotal mdecDiscountTotal
  • End Get
  • End Property

39
Add a Summary Button to the frmSale
Practice expanding Class codes Page 256-257
40
Friend Protected Programming Elements
  • The Friend keyword confers friend access on one
    or more declared programming elements. Friend
    elements are accessible from within the program
    that contains their declaration and from anywhere
    else in the same assembly.
  • The Friend keyword can be used in conjunction
    with the Protected keyword in the same
    declaration. This combination confers both friend
    and protected access on the declared elements, so
    they are accessible from the same assembly, from
    their own class, and from any derived classes.

41
Constructors and Destructors
  • Constructor Method that automatically executes
    when an object is instantiated
  • Created by writing a Public Sub New procedure
  • Sub New()
  • 'Constructor with empty argument list
  • End Sub
  • Sub New(ByVal Title As String, ByVal Quantity As
    Integer, ByVal Price As Decimal)
  • 'Assign property values
  • Me.Title Title
  • Me.Quantity Quantity
  • Me.Price Price
  • End Sub

When the class has both, the program that create
the object can choose which method to use
Attention on Me. The class in which the Sub is
42
Constructors and Destructors, Cont Destructor
  • Method that automatically executes when an
    object is destroyed
  • Create by writing a Finalize procedure
  • Usage discouraged by Microsoft
  • A C Compatibility concern

43
Overloading
  • Overloading means that 2 methods have the same
    name but a different list of arguments (the
    signature)
  • Create by giving the same name to multiple
    procedures in your class module, each with a
    different argument list

44
Parameterized Constructor
  • Constructor that requires arguments
  • Allows arguments to be passed when creating an
    object
  • mStudentBookSale
  • New StudentBookSale( txtTitle.Text,
    CInt(txtQuantity.Text),
  • CDec(txtPrice.Text))
  • VS. mBookSale New BookSale()
  • mBookSale.Title txtTitle.Text
  • mBookSale.Quantity CInt(txtQuantity.Text)
  • mBookSale.Price CDec(txtTitle.Price)
  • Can be used to assign initial property values

45
Garbage Collection
  • Feature of .NET Common Language Runtime (CLR)
    that cleans up unused components
  • Periodically checks for unreferenced objects and
    releases all memory and system resources used by
    the objects
  • Microsoft recommends that you depend on .NET
    Garbage Collection rather than Finalize procedures

46
Inheritance Implemented
  • New class can
  • Be based on another class (base class)
  • Inherit the properties and methods (but not
    constructors) of the base class, which can be
  • One of the VB existing classes
  • Your own class
  • Designate Inheritance by adding the Inherits
    statement referencing the base class

47
Overriding Methods
  • Methods created in subclass with the same name
    and the same argument list
  • Subclass will use the method in its own class
    rather than that in the base class
  • To override a method
  • Declare the base class method with the
    Overridable keyword In Base Class
  • Public Overridable Function ExtendedPrice() AS
    Decimal
  • Declare the subclass method with the Overrides
    keyword In Inherited Class
  • Overrides Function ExtendedPrice() As Decimal

48
Creating a Base Class Strictly for Inheritance
  • Classes can be created strictly for inheritance
    and are never instantiated
  • Subclasses are created and instantiated which
    inherit the base class properties and methods
  • For such a base class include the MustInherit
    modifier on the class declaration Public
    MustInherit Class XX

49
Referencing Values on a Different Form
  • Use the identifier for the other form's instance
    to refer to controls on different form
  • General Syntax
  • Example

FormInstance.ControlName.Property
Dim frmSumInstance as New frmSum(
) frmSumInstance.lblTotal.TextFormatCurrency(mdec
Total)
50
Object Browser
  • Use it to view the names, properties, methods,
    events and constants of VB objects, your own
    objects, and objects available from other
    applications
  • Accessed
  • Tab in Editor Window
  • View menu, Other Window, Object Browser

51
Opening Object Browser from Toolbar
52
Object Browser
53
Examining VB Classes
Members of System.Windows.Forms.MessageBox Class
54
Examining VB Classes (cont.)
Display the MessageBoxButtons Constants
Write a Comment
User Comments (0)
About PowerShow.com