APII 3 OOP

Embed Size (px)

Citation preview

  • 7/25/2019 APII 3 OOP

    1/33

    4/22/20

    Object Oriented Programming

    Using Visual Studio

    Objectives

    To :

    Learn about Classesand Objects

    CreateYour Own Classes

    Learn about Enumerated Types

    To Focus on Program Design and Problem Solving:BankTeller Application

    To undertakeManual Software Testing

    OOP

    2

    Classes and Objects

    OOP

    3

    Object Oriented Programming

    A way of designing and coding applications thatfocuses on objects and entities in real-worldapplications.

    Objects

    Reusable software components that model items inthe real world.

    e.g. wecanmodel a GPA calculator,or a tax calculator

    Self-contained modules that combine data andprogram code which pass strictly defined messagesto one another.

    OOP

    4

  • 7/25/2019 APII 3 OOP

    2/33

    4/22/20

    Objects

    An object can also be defined as acontainer formemberssuch as properties, fields, methods, andevents

    Often represents an entity in a real-worldapplicatione.g.:

    If creating an car dealership application, the entitiesmight have names like vehicle, customer, salesperson,manager,and vehicle inventory.

    If creating a GUI, the objectsmight be button, text box,list box, label,and radio button.

    OOP

    5

    Forms and Controls as Objects

    Twokindsof objects you may use in VBare:

    Formsand

    Controls

    Aform is a virtual blank space to design the userinterfacefor a VBapplication

    Controls are the tools that you use to construct theuser interface e.g.

    command button

    textbox

    OOP

    6

    VB objects naming practice:

    Start the name witha standard object abbreviation

    cmd = command button, txt = text box, frm = form.

    Finish the name with a descriptive word of theobjectspurpose e.g.

    cmdCancel

    frmMain.BackColor = vbRed

    txtState.Text= ""

    Spaces and special characters are not allowed inanobjectsname.

    OOP

    7

    Features of Objects

    The programmer can manipulatethe object through the use of threekey object features:

    properties/ attributes

    methods/ behaviour

    events

    OOP

    8

  • 7/25/2019 APII 3 OOP

    3/33

    4/22/20

    Objects

    Anobject

    hasattributes: characteristicsthat cantakeonvalues

    a vehicle objectsattributesinclude make, model, and colour

    hasbehaviours:actionsthat can be carried out on theobject

    A vehicle object might have behaviours such as start, stop,and turn.

    canraiseevents: notif icationsof a change of state i.e.events representresponses by the object to externalactions.

    A Button object in .NET raises a Click event when the user

    clicksthe button. OOP

    9

    Object Properties

    A property isa named attributeof an object.

    Using ananalogy to English grammar, if an object isthought of as anoun, then apropertymay bethoughtof asanadjective.

    Used to change the appearance of objects.

    An example of the relationship between objectsand propertiesusing an everyday object:

    shirt.colour = Green

    shirt.wash = Clean

    We use dot (.) notation OOP

    10

    Setting Values of Properties

    Properties may be set during design time,in the PropertiesWindow

    Design Time: when you are designing theproject and adding code

    Some properties may be set or modifiedduring runtime.

    RunTime: whenyouclick the Run icon

    OOP

    11

    Object Event

    Notificationsof a change of state.

    Representstheresponse by the object to an external action.

    An actiontakenby the object whennotif ied by a message

    User actions takenon the object that provokesa response f romthe object.

    Examples

    A football: kicking, throwing, holding etc.

    Cat: feeding,petting, calling etc.

    mouse click, formload, or key press.

    VBexamplePrivate Sub cmdSubmit_Click()

    End SubOOP

    12

  • 7/25/2019 APII 3 OOP

    4/33

    4/22/20

    frommsdn.microsoft.com

    See also the document titledAPII 3 OOP -Methods vs Events, an excerpt from JohnSweeneys Visual Basic for Testersbook

    Properties vsMethods vsEvents

    OOP

    13

    Closer Look: UnderstandingProperties, Methods, and Events All objects in the Visual Basic language have their own

    properties,methods,andevents.

    Properties can be thought of as theattributes of an object,methodsasitsactions, and eventsasitsresponses.

    An everyday object such as a helium balloon also hasproper ties,methods, and events.

    Aballoon'spropertiesinclude

    visible attributessuchasitsheight, diameter, and colour.

    Other propertiesdescribeitsstate (inflatedor deflated),or

    attributesthat are not visible, suchasits age.

    All balloonshave these properties, although the valuesof these

    propertiesmay differ fromoneballoonto another.OOP

    14

    Closer Look: UnderstandingProperties, Methods, and EventsA balloon also has knownmethodsor actionsthat it can

    perform. It has

    an inflatemethod (filling it with helium),

    a deflatemethod(expelling its contents),and

    a risemethod (letting go of it).

    a MakeNoisemethod

    Again, all balloonscanperformthese methods.

    Balloonsalsohaveresponsestocertainexternalevents.

    For example,a balloonrespondsto

    theeventof being puncturedby deflating,or to

    theeventof being releasedby r ising.

    OOP

    15

    Closer Look: UnderstandingProperties, Methods, and EventsProperties

    If you could program a balloon, the Visual Basic code mightresemble the following "code," which sets a balloon'sproperties.

    Balloon.Colour = Red

    Balloon.Diameter = 10

    Balloon.Inflated = True

    Notice the order of the code - the object (Balloon), followed bythe property (Colour), followed by the assignment of the value

    (= Red). You could change the balloon's colour by substituting a

    diff erent value.OOP

    16

  • 7/25/2019 APII 3 OOP

    5/33

    4/22/20

    Closer Look: UnderstandingProperties, Methods, and EventsMethods

    A balloon'smethodsare calledasfollows.Balloon.Inflate

    Balloon.Deflate

    Balloon.Rise(5)

    The order resembles that of a property- the object (a noun),followed by the method (a verb).

    In the third method, there is an additional item, calledanargument,whichspecifiesthe distancethe balloonwill rise.

    Some methods wil l have one or more arguments to furtherdescribethe actionto be performed.

    OOP

    17

    Closer Look: UnderstandingProperties, Methods, and EventsEvents

    The balloon might respond to an event asfollows.

    Sub Balloon_Puncture()

    Balloon.MakeNoise("Bang")

    Balloon.Deflate

    Balloon.Inflated = False

    End Sub

    The code describes the balloon's behaviour when aPunctureeventoccurs.

    call the MakeNoise method with an argument of "Bang" (the type ofnoise to make), thencall the Deflate method.

    Since the balloon is no longer inflated, the Inflated property is setto False. OOP

    18

    Event Handlers

    NB:

    Event handlersare also methods, but theyhave a special role - to respond to eventmessages passed to your application f rom theoperating system.

    OOP

    19

    Object-Oriented Event-DrivenProgramming (OOED)

    OOED uses objects in the program and runs onlyafter the eventsoccur

    OOEDiseasy to work with

    Users can combine multiple objects to create newsystemsor extend existing ones

    OOP

    20

  • 7/25/2019 APII 3 OOP

    6/33

    4/22/20

    Classes

    OOP

    21

    What is a Class?

    Classes are the basic elements of object-orientedprogramming, which in turn makesit possible for programmersto build rich, robust applications.

    Aclassis a designtemplatefor objects

    Defineswhich properties, methods, and eventscan be applied to itsobjects

    Objectsare also knownas instances

    A classisdefined using the Class keyword.

    E.g. every form that you add to an applicationis defined by a class,suchasthefollowing:

    Public Class Form1

    End Class

    OOP

    22

    Class Examples

    Each control in the Visual Studio Toolbox window wasdefinedby a class.

    For instance,the Buttoncontrol wasdesigned asa class

    Whenyoudrag a button fromthe ToolBox onto a form, itbecomesanobject.EachButtonobject canbe assigned unique property valuese.g.:

    ForeColor: Blue

    Text:ClickMe

    A TextBoxcontrol haspropertiessuchas:Name, Text, V isible, andForeColor.

    All TextBox objectshave theseproperties.

    OOP

    23

    Namespaces

    The Microsoft .NET Framework contains a largelibrary ofclasses that make it possible to write applicationsfor desktopcomputing, mobile applications, and the Web.

    The classesare grouped by similarity into namespacesto makeit easier to find them.

    Anamespace is a logical container that holds classes ofsimilar types.

    For example,

    theSystem.Collections namespace contains classes related to

    building collections(arrays,lists, dictionaries, sets).The System.Windows.Formsnamespace contains classes related to

    building desktopapplicationsfor Windows.OOP

    24

  • 7/25/2019 APII 3 OOP

    7/33

    4/22/20

    Creating Objects

    A class must already be defined before you cancreate one or moreobjectsof the class type (akainstancesof the class, orclass instances).

    Use the Newoperator, as in:

    Dim fresher AsNewStudent

    The NewoperatortellsVBto createan object inmemory.

    It is required whencreating an object (thisrule applies to allobjectsexceptStringobjects).String objects are a special case of reference types declared as

    follows:

    Dim strName As String

    Dim strCity As String = Mombasa

    OOP

    25

    Creating Objects

    Dim fresher As New Student

    Thislineof codeanbe separated into twosteps:

    Dim fresher As Student

    Thisvariabledoesnotreferenceanyobjectat thispoint - itonly hasa data type.

    fresher = New Student

    creates an instance of the class (i.e. a new object) andassignsit to the variable.

    The variable containsa referenceto the object.

    OOP

    26

    Visual Studio Controls

    Visual Studio creates instancesof controls when you drag them from the ToolBoxonto a form.

    For example, the following code waswritten to a formsdesigner file whena buttonwascreatedand certainpropertieswere set in thedesigner window:

    Me.btnOk = New Button()

    Me.btnOk.Location = New System.Drawing.Point(43, 48)

    Me.btnOk.Name = btnOk

    Me.btnOk.Size = New System.Drawing.Size(75, 23)

    Me.btnOk.Text = OK

    Notice how the first line uses theNew operator to create an instance of the Buttonclass.

    Thenvariousproperty valuesare assigned to the button (Location, Name, Size, andText).

    OOP

    27

    Nothing

    When a reference type variable has not beeninitialised it has a null value indicated by the

    Nothing keyword.

    An object variable that is null must be initialisedbefore it canbe used

    Thiscode generatesa runtimeerror:myObject = Nothing

    myObject.Print( )

    Asdo these linesof code:Dim fresher As Student

    fresher.PrintCourses() OOP

    28

  • 7/25/2019 APII 3 OOP

    8/33

    4/22/20

    Nothing

    If your code needs to know whether a variable hasbeen initialised, you can compare the variable to thekeywordNothing.

    If fresher Is Nothing Then

    ' must initialise the variable

    fresher = New Student

    End If

    OOP

    29

    Value Type

    There are two general categoriesof Visual Basic data types:

    valuetypesand

    reference types.

    Valuetypes include all the number types, such as Integer andDecimal, aswell asDouble and Boolean.

    These typesuse a standard-size storage location.

    Thevariableholdsitsowndatainasinglememorylocation

    Valuetypesdonotrequireanyinitialisation.

    Assoonas youdeclare them, they haveimmediate storage.

    Easy to use, consume little memory, and are the simplest tounderstand whenusing the assignment operator (=).

    OOP

    30

    Value Types

    Example:

    Dim Count As Integer

    Count = 5

    OOP

    31

    Value Types

    When you assign one value type to another using theassignment operator (=), a copy is made of the datain the variable on the right-hand side.

    The data is copied into the variable on the left-handside.Dim mCount As Integer = 25

    Dim temp As Integer = mCount

    mCount is copied to temp

    If a new value is later assigned to temp, mCount is notaffected:

    temp = 40' mCount still equals 25OOP

    32

  • 7/25/2019 APII 3 OOP

    9/33

    4/22/20

    Reference Type

    Whenever you create an instance of a class(an object) and assign it to a variable, yourvariable isa referencetype.

    A variable declared as a reference type doesnotdirectlyholditsdata.

    Instead the variable points to (holds areference or address of) an object storedsomewhere else in memory

    OOP

    33

    Reference Type

    Classesand Arraysare examplesof reference types.

    When an object is created by invoking theNewoperator, the .NET runtime reserves space in memoryfor the object.

    Theaddress of the object is stored in areferencevariable.

    Takesmoreprocessing time thanfor value types, but

    Allows .NETto reclaim the storage used by the objectwhenitisnolongerneededbytheprogram.

    OOP

    34

    Reference Type ExampleWhat does the following piece of code do?

    Dim P As New Person

    creates a Person object

    assigns the objects reference to P

    P.Name = "Fred Omar

    assigns a value to the objects Name

    property

    Omar

    Pcontainsa reference to the data, not the data itself.If at any time in the future, the Person object is no

    longer needed, we can assign a value of Nothing to P

    i.e. P = NothingAssuming that no other references to the same Person

    object existed, a special utility in the .NET runtime

    called the garbage collectorwould eventually remove

    the objectfrom memory.OOP

    35

    Assigning Objects

    The assignment operator, (=),copies a reference,not a value:

    Dim Y As New Account

    creates an Account object

    Dim X As Account

    creates object/reference type variable

    whose data type is Account. It is

    uninitialised (has no reference)

    X = YNow, Both X and Y reference the same

    objectOOP

    36

  • 7/25/2019 APII 3 OOP

    10/33

    4/22/20

    Assigning ObjectsArray Example

    The following code creates an array ofintegers namedtests, fills the array, andassigns the array to the variable namedscores:

    Dim scores() As Integer

    Dim tests() As Integer =

    {80, 95, 88, 76, 54}

    scores = testsOOP

    37

    Assigning ObjectsArray Example

    After this code executes, the same array isreferenced by bothscoresandtests

    OOP

    38

    Array Example

    The following code can be used to show that thetwoarraysshare thesame memory.

    scores(2) = 11111

    MessageBox.Show(tests(2).ToString())

    ' displays 11111

    By assigning a new value to scores(2), weautomatically assign thesame valueto tests(2):

    OOP

    39

    Assigning Objects

    This type of dual reference can lead to a commontype of programming error known asa side effect

    As it causes unwanted effects by changing variables in away that canfool a programmer.

    Assigning one reference type to another using the=operator leads to both variables referencing thesame object.

    Thusa change to one variable will cause a change to

    the other (this is the side effect)Code containing side eff ects is very dif ficult to debug.

    OOP

    40

  • 7/25/2019 APII 3 OOP

    11/33

    4/22/20

    More on ArraysUsing a Loop to Copy an Array

    If you want to copy the contents of one array toanother, you can use a loop to copy the individualelements.

    First, youreserve spacein the scoresarray.

    Thenyoucopy the data.

    Dim scores(tests.Length - 1) As Integer

    For i As Integer = 0 To tests.Length - 1

    scores(i) = tests(i)

    NextOOP

    41

    More on ArraysUsing a Loop to Copy an Array

    The result af ter copying the array.

    OOP

    42

    More on ArraysUsing a Loop to Copy an Array

    The following code showsthat the two arraysdo notshare thesame memory.

    scores(2) = 11111

    MessageBox.Show(tests(2).ToString())

    displays 88

    When a new value is assigned to scores(2), thevalueof tests(2) isunchanged:

    OOP

    43

    Object.Clone

    The Object.Clone method is a more general way ofcopying the data fromany referencetypeto another.

    It

    Copiesanobject or anarray

    ReturnsanObject

    The following statement copies the array from ourscoresand testsarraysexample:

    scores = CType(tests.Clone(), Integer())

    OOP

    44

  • 7/25/2019 APII 3 OOP

    12/33

    4/22/20

    CType Function

    Returns the result of explicitly converting anexpression to a specified data type, object,structure,class, or interface.

    Syntax:

    CType(expression, typename)

    You can also perform a conversion to a specificdata type using functions

    CByte,

    CDbl, and

    CInt. OOP

    45

    Object.Clone

    scores = CType(tests.Clone(), Integer())

    The Clone methodreturns anObject, so the returnvalue must be cast into an Integer arraywhenOption Strictis ineffect.

    asscoresis an integer array.

    Option Strictprevents program from automaticvariable conversions, i.e. implicit data typeconversions

    OOP

    46

    Object.Clone

    Heresanother example, using two Personobjects:

    Copying a Personobject:

    Dim P As New Person

    P.LName = Omari

    Dim S As Person

    S = CType(P.Clone(), Person)

    OOP

    47

    Comparing Standard .NET Objects

    All standard .NET objectscan be compared forequality by by using the= operator or calling theEqualsmethod.

    Thisis thecase for strings:

    Dim A As String = abcde

    Dim B As String = "abcde"

    If A = B Then ...' result: True

    If A.Equals(B) Then ...' result: True

    OOP

    48

  • 7/25/2019 APII 3 OOP

    13/33

    4/22/20

    Comparing Standard .NET Objects

    You can also comparestrings by calling theCompareTomethod

    If X < Y, CompareTo returns a negative value

    If X = Y, CompareTo returns zero

    If X > Y, CompareTo returns a nonzero positive value

    Example:

    Dim A As String = "abcde"

    Dim B As String = "abd"

    Dim result As Integer = A.CompareTo(B)

    ' result is assigned a negative value

    OOP

    49

    Comparing Standard .NET Objects

    Dim A As String = abf

    Dim B As String = abd

    Dim result As Integer = A.CompareTo(B)

    ' result = positive value

    Dim A As String = abd

    Dim B As String = abd

    Dim result As Integer = A.CompareTo(B)

    ' result = zero

    OOP

    50

    Comparing User Class Types

    Your own classes, by default, will not use EqualsandCompareToeffectively.

    Consider the following comparison of two Studentobjects:

    Dim s1 As New Student(1001)

    Dim s2 As New Student(1001)

    If s1.Equals(s2) Then ...

    The call to Equals will return

    False, even though the students

    apparently have the same ID numberOOP

    51

    Comparing User Class Types

    Similarly, calling s1.CompareTo(s2) below is notmeaningful:

    Dim result As Integer = s1.CompareTo(s2)

    This meansthat youcannot effectively sort an arrayof Students.

    The following 2 slides showsan example of how tocompare user classtypes

    OOP

    52

  • 7/25/2019 APII 3 OOP

    14/33

    4/22/20

    Comparing User Class TypesUsing CompareToClass Student

    Implements IComparable

    class implements the IComparable interface. An

    interface defines a set of methods and properties

    that can be implemented by other classes.

    Public Property Id As String

    Public Property LastName As String

    Public SubNew(ByVal pId As String, ByVal

    pName As String)

    Id = pId

    LastName = pName

    End Sub OOP

    53

    continued on next slide

    Comparing User Class TypesUsing CompareToPublic Function CompareTo(ByVal obj As Object) As Integer

    _Implements IComparable.CompareTo

    The CompareTo method in this class implements the

    CompareTo method specified in the Icomparable Interface

    Dim S As Student = CType(obj, Student)

    casts the obj parameter into a Student object, allowing

    us to refer to the Id field in the next line:

    Return Me.Id.CompareTo(S.Id)

    The Id value of the current student (identified by Me)is

    compared to the Id value of the student who was passed as

    the parameter to this method.

    End Function

    End Class

    OOP

    54

    Creating Your Own Classes55

    OOP

    Creating Your Own Classes

    The.NETFramework comeswith its ownset of classes.

    Youcan also design and build your ownuser-defined(orcustom) classes.

    You create a class in Visual Basic by coding aclassdefinition.

    Syntax

    Public Class ClassName

    class members hereEnd Class

    OOP

    56

  • 7/25/2019 APII 3 OOP

    15/33

    4/22/20

    Creating Your Own Classes

    FromtheMenu:

    Select Projectonthe menubar, then

    select AddClass.

    TheAdd New Itemdialog box appears.

    Or

    IntheSolutionExplorerwindow:

    Right-click the Project name,

    select Add

    select Class.

    OOP

    57

    Creating Your Own Classes

    The keywordPublicisanaccess specifier.

    It tells VB that the class will be visiblefromall partsof your application.

    i.e. itwill bepossibletocreateobjectsthatusethisclassname.

    OOP

    58

    Class-Level Variables

    Class-levelVariablesare those variablesdeclaredinside a classbut outside of any methodsin the class

    They are thusvisible to all methodsin theclass.

    (Local variablesare declared inside methods and arevisibleonly inside themethod)

    Syntax of a Class-level Variable:AccessSpecifier name As DataType

    Example:Private myIdNumber As String

    OOP

    59

    Class-Level Variables

    Public Class Student

    Private mIdNumber As String

    Private mLastName As String

    Private mTestAverage As Double

    End Class

    NB:

    A class definition does not, by itself, create an instance

    of the class. It establishes a blueprint for the classs organisation, which

    makesit possible for you to write other code that creates anobject of this type OOP

    60

  • 7/25/2019 APII 3 OOP

    16/33

    4/22/20

    Encapsulation

    The capability of an object tohide its internalworkingsfromother objects.

    The programmer needsNOTknow what is going oninside the object, but only how to work with theobjectspropertiesand methods.

    In object-oriented programming, the encapsulationprinciple says that you should bundleattributesandbehavioursinsideaclass.

    Think of a class as a container that encapsulateseverything inside for easy transportingand usage.

    OOP

    61

    Encapsulation

    Encapsulation is the processof integrating dataand code into one entity: anobject.

    i.e. the object comprises all the data it usesand itsfunctionality.

    E.g.:

    Data for an employee includes

    name,date hired,and title

    Thefunctionality includes

    methodsfor adding and removing employees.

    OOP

    62

    Encapsulation

    Your application, as well as external applications,could then work with the employee data through aconsistent interface - the Employee objectsinterface.

    An interface is a set of exposed functionality -basically, code routines that define methods,properties, and events.

    OOP

    63

    Information Hiding

    Theinformation hiding principle,which is closelyrelated to encapsulation, says that certain classmembersshouldbevisible only to methodsinsidetheclass.

    Usually, this applies tovariables, which are labeledasPrivate.

    A class-level variable could be declared Public, socode anywhere in an application (e.g. any classes)

    could accessit directly.But doing so would violate the information hiding

    principle.OOP

    64

  • 7/25/2019 APII 3 OOP

    17/33

    4/22/20

    Information Hiding

    Instead, we usepublic methods and propertiestodefinean interface, or public view of a class.

    Other information, such as variables, remain hiddenby using the Private keyword.

    A variable isusually declared asPrivate.

    It may be accessed only by statements inside methodsbelonging to thesame class.

    i.e. hidden (private) memberscan be accessed only by othermethodsinthesameclass.

    This is a good idea because it leads to more reliableprogramsthat are easier to debug.

    NB:Many software engineersconsiderencapsulationand informationhiding to be thesame.

    OOP

    65

    Object Methods

    An action (or named executable unit) that implements somebehaviour of a class.

    Simply put, it is asetof predefinedactivities that an objectcancarry out.

    i.e. a method isa verbthat can be carried out by theobject.

    The syntax for using an objectsmethod is:object.method

    For the various VB objects, there are usually several methodsalready available.

    Advanced programmerscancreate their ownmethods.

    OOP

    66

    Methods Example

    Real life example

    dog.eat

    dog.bark

    dog.run

    A Visual Basic example frmMain.hide

    OOP

    67

    Methods

    There are twotypesof methods:

    Instancemethod called using an instance of theclass(object)

    Dim S As New Student

    S.Print()

    Sharedmethod called using the classname

    Dim arrayScores() As Integer = {62, 45, 89}

    Array.Sort(arrayScores)

    OOP

    68

  • 7/25/2019 APII 3 OOP

    18/33

    4/22/20

    Properties

    In VB,a property is a special type ofmethod thatuses the same member name forgetting and settingavalue

    Whereas methods are the implementation of classbehaviours, properties are implementationsof classattributes.

    Button objects, for example, have a number ofproperties that are listed in the Properties window inVisual Studio.

    A Property name lookslike a variable to usersof the

    class OOP

    69

    Declaring a Property

    Public Property PropertyName() As

    DataType The brackets after

    PropertyName are optional

    Get

    '(code that returns data)

    End Get

    Set(value As DataType)

    '(code that assigns value to a class

    variable)

    End Set

    End Property OOP

    70

    Property Definition Code Example

    class Student

    Private mLastName As String

    Public Property LastName As String

    Get

    Return mLastName

    End Get

    Set(ByVal value As String)

    mLastName = value

    End Set

    End Property

    End Class OOP

    71

    Auto-Implemented Property

    A property that is defined by only a single line of code

    Getsand setsvalue of a hidden private field

    Youdonthavetocreateaprivatememberfieldtoholdthepropertydata.

    There are two general formats:Public Property PropertyName As DataType

    Public Property PropertyName As DataType = InitialValue

    You can follow each property name with optional parentheses:PropertyName()

    Example:Public Property IdNumber As String

    OOP

    72

  • 7/25/2019 APII 3 OOP

    19/33

    4/22/20

    Auto-Implemented Property

    Public Property PropertyName As DataType = InitialValue

    Init ialValueisan optional value that youcan assign tothe property when it is created.

    When you declare an auto-implemented property,Visual Studio automatically creates a hidden privatefield called a backing field that contains theproperty value.

    The backing fields name is an underscore and theproperty name.

    E.g., if you declare anautoimplemented property named ID,

    itsbacking f ield isnamed _ID. OOP

    73

    Auto-Implemented Property

    Examples

    auto-implemented properties that could be used in theStudent class:

    Public Property IdNumber As String

    Public Property LastName As String

    Public Property TestAverage As Double = 0.0

    Now that we have auto-implemented properties, whydo we need to create the longer property definitions?

    Because they allow usto include range checking and othervalidationsondata assigned to the property.

    A ReadOnly property must be f ully codedit cannot be

    auto-implemented. OOP

    74

    Getting and Setting PropertyValues

    Before accessing a property, you mustdeclareaninstanceof theclass (object) that containsthe property.

    We could place the following statementanywhere in the program outsidetheStudentclass:

    Dim fresher As New Student

    OOP

    75

    Getting and Setting PropertyValues

    The Set section of the property procedureexecutes when a value is assigned to theproperty.

    The following statement sets the value ofLastName:

    fresher.LastName = Odhis

    Thus executing the following statement inside

    the property procedure:

    _LastName = valueOOP

    76

  • 7/25/2019 APII 3 OOP

    20/33

    4/22/20

    Getting and Setting PropertyValues

    TheGetsection of a property procedure executeswhen a program needs to have a copy of theLastName.

    Suppose thatoutsidetheStudentclass, we wrote thefollowing statement, which copies the studentsLastName value to a TextBox:

    txtLastName.Text = fresher.LastName

    The following statement inside the propertyprocedure would execute:

    Return _LastNameOOP

    77

    Input Validation in Properties

    A property can be very useful whenvalidating valuesassigned to it.

    In the foll owing example, which implementsthe TestAverage property, the value assigned totheproperty must be between0.0 and 100.0:

    Public Property TestAverage As Double

    Get

    Return mTestAverage

    End Get

    Set(ByVal value As Double)

    If value >= 0.0 And value

  • 7/25/2019 APII 3 OOP

    21/33

    4/22/20

    Object Initialisers

    The following statement creates and initialises aStudentobject using control values:

    Dim aStudent As New Student With

    {

    .IdNumber = txtIdNumber.Text,

    .LastName = txtLastName.Text,

    .TestAverage = CDbl(txtAvg.Text)

    }

    OOP

    81

    Assigning Object Variables

    There are well-defined rules for assigningvaluesofstandarddatatypesto eachother.

    E.g. we can assign an Integer expression to aDoublevariable, because VB automaticallyexpands the integer expression to typeDouble.

    There are similar but more restrictive rules forassigningclassobjects to eachother.

    OOP

    82

    Assigning Object Variables

    In nearly all cases, you must perform a cast fromone type to anotherexcept in the following twocircumstances

    1. Twovariableshavethe same classtypeDim student1 As new Student

    Dim student2 As Student = student1

    2. The twovariables are of different types, but thevariableonthe left istypeObjectDim student1 As New Student

    Dim obj As Object = student1

    The second opt ion is allowed because Object is a very general type that a ccepts any type of a ssignment.

    83

    Not ice here we are assigning one reference variable (not object) to another.

    Assigning Object VariabesNote:

    The expression on the right side of the =operator doesnot have to be a variable;

    it might be a property name or method call.

    For example, a method namedGet-Studentreturns a Student object, which cannot beassigned directly to a String variable:

    Dim temp As String = GetStudent("12345")'error

    OOP

    84

  • 7/25/2019 APII 3 OOP

    22/33

    4/22/20

    Assigning Object VariabesNote:

    We can assign the Student object to a string variableif we call the objectsToString method:

    Dim temp As String = GetStudent("12345").ToString()' ok

    Converting any object to a string is easy because allclassesimplicitly contain aToStringmethod.

    But if you want to convert to some other type, youmay have to call the CType function.

    OOP

    85

    Assigning Object Variabes

    In nearly all cases, you must perform a cast from one

    typeto another

    E.g., the ListBox controlsSelectedItem propertyreturnsan object.

    If you want to assign this object to a Studentvariable,youmust call theCType function:

    The variable onthe right istype ObjectDim selStudent As Student = lstStudents.SelectedItem

    Will NOT compile if Opt ion Stric t is turned on

    Dim selStudent As Student =

    CType(lstStudents.SelectedItem, Student)OOP

    86

    Three-Tier Application Model

    The basic design that most businessapplicationstoday follow.

    Each tier contains classes that callmethodsin the tier below it.

    PresentationTier objectsthat interactwith theuser

    Middle Tier core information, such as calculations and

    decisionmakingData AccessTier interactdirectly withdata source

    OOP

    87

    The Presentation Tier(User Interface Tier/User Services Layer)

    Consistsofall objectsthatinteractwiththeuser.

    Visual Basic usesa classto define a form, aswell asthe variouscontrolson a form.

    Code that you write inside the form of anapplicationbelongshere e.g. all the formclasss:

    eventhandler procedures,

    class-level variables, and

    other subprocedures.

    OOP

    88

  • 7/25/2019 APII 3 OOP

    23/33

    4/22/20

    The Middle Tier(Business Logic Tier / Business Services Layer)

    Consists of classes that provide core information tothe application, such as essential calculations anddecisionmaking.

    They often embody the business rules of anorganisation Including operational principles that are common to

    multipleapplications.

    Theseclassesdonotinteractwiththeuser. Instead, they contain methods and properties that are

    called by classesin thepresentationtier.

    OOP

    89

    The Data Access Tier(Data Services Layer)

    Contains classes that interact directly with a datasource.

    Later we will create classes for this tier that readand writeto databases.

    OOP

    90

    Constructors

    A methodthatrunsautomaticallywhenaninstanceoftheclassiscreated.

    In Visual Basic, a constructor is always namedNew.

    Constructors typically initialise classmember variablesto default values, but they can also be used toperformany required classinitialisation.

    E.g. if a class is connected to a network connection, the

    constructor could be used to open a connection to aremote computer.

    OOP

    91

    Constructors

    A default constructoris a constructor with noparameters.

    To create a simple one for the Student class thatassigns a default value to themIdNumber datamember:

    Public Sub New()

    mIdNumber = "999999"

    End Sub

    With this constructor in place, if a client programcreates a new Student object, we know for certainwhat value theobjectsmIdNumberwill contain.OOP

    92

  • 7/25/2019 APII 3 OOP

    24/33

    4/22/20

    ParameterisedConstructor

    A classmay contain more than one constructor.

    Thus apart from the default constructor, youmay want to create a parameterisedconstructor(a constructor with parameters).

    OOP

    93

    Assigns values to each of the Student class-levelvariables:

    Public Sub New(ByVal pIdNumber As

    String, ByVal pLastName As

    String,ByVal pTestAverage As Double)

    mIdNumber = pIdNumber

    mLastName = pLastName

    mTestAverage = pTestAverage

    End Sub

    ParameterisedConstructorExample

    OOP

    94

    Will This Code Compile?

    OOP

    95

    Public Sub New(ByVal pIdNumber

    As String, ByVal pLastName As

    String, ByVal pTestAverage As

    Double)

    pIdNumber = IdNumber

    pLastName = LastName

    pTestAverage = TestAverage

    End Sub

    Will This Code Compile?

    OOP

    96

    The code compilescorrectly

    However, the operands in the assignmentstatementsare reversed.

    They copy the valuesfromthe propertiesto theparameters.

    The result is that the constructor does not workproperly: the values passed to the constructor

    are not assigned to the classproperties.

  • 7/25/2019 APII 3 OOP

    25/33

    4/22/20

    When coding a constructor,DO NOT use the samename for the constructor parameters that you use forclasslevel variables and properties:

    Public Sub New(ByVal IdNumber As String,

    ByVal LastName As String, ByVal TestAverage

    As Double)

    IdNumber = IdNumber

    LastName = LastName

    TestAverage = TestAverage

    End Sub

    ParameterisedConstructorParametreNaming

    OOP

    97

    Default Constructors

    If your class does not contain any constructors,VB creates an invisible empty defaultconstructorfor you.

    This is for convenience, so you can declare anobject like this:

    Dim secondYear As New Student

    But if you add a parameterised constructor tothe class, a default constructor is NOTCREATEDautomatically for you.

    OOP

    98

    Default Constructors

    Suppose thiswere the only constructor we had in theStudent class:

    Public Sub New(ByVal pIdNumber As

    String, ByVal pLastName As String,

    ByVal pTestAverage As Double)

    ' (lines omitted)

    End Sub

    Why would thefollowing statement not compile?Dim objStudent As New Student

    OOP

    99

    Constructors with OptionalParameters

    An optional parameter does not require thecalling method to pass a correspondingargument value.

    Sometimes you will want to create instances ofa classusing varying amountsof information.

    You can declare optional parameters in anymethod (including constructors) using the

    Optional keyword, as long as youassign eacha default value.

    OOP

    100

  • 7/25/2019 APII 3 OOP

    26/33

    4/22/20

    Constructors with OptionalParameters

    Public Sub New(ByVal pIdNumber As

    String,Optional ByVal pLastName As

    String = , Optional ByVal

    pTestAverage As Double = 0.0)

    the pLastName and pTestAverage

    parameters are optional

    IdNumber = pIdNumber

    LastName = pLastName

    TestAverage = pTestAverage

    End Sub

    OOP

    101

    Constructors with OptionalParameters

    Dim A As New Student("200103")

    Dim B As New Student("200103",

    Odhis")

    Dim C As New Student("200103",

    Odhis", 86.4)

    All three statements are valid ways of declaringStudent objects as the pLastName andpTestAverage parameters are

    optional

    OOP

    102

    Constructors with OptionalParameters: Rules

    1. Once a parameter is labeled optional, allsubsequent parameters in the methods parameterlist must also be labeled the same way.

    So let the optional parametresbe the last inthe list

    2. All optional parameters must be assigned defaultvalues.

    When the Visual Studio editors Intellisense tooldisplays a methods parameter, optionalparametersappear inside square bracketse.g.:

    OOP

    103

    Do Labs:

    1-1: Creating a Student Class

    1-2: Adding a parameterised constructor

    Lab104

    OOP

  • 7/25/2019 APII 3 OOP

    27/33

    4/22/20

    Lab 1-1

    Creatinga Student Class

    Two-tier application(Presentation& Middle)

    OOP

    105

    Lab 1-2

    Adding a parameterised constructorto the Student classThree parameters:

    1. ID number,

    2. last name,

    3. test average

    OOP

    106

    ReadOnly Property

    A property that allows methods to get the currentproperty value, but not change it

    Example:

    Public ReadOnly Property Count As Integer

    Get

    Return mCount

    End Get

    End Property

    OOP

    107

    Enumerated Types

    List of symbolic namesassociated with integer constants

    Makesprogramsmore readable and maintainable

    by giving namesto what would otherwise be integers.

    E.g.

    Consider an application that works with four differentaccount types,numbered 0, 1, 2, and 3.

    It might be diff icult, when looking at programcode, to recallwhichinteger corresponded to eachtype of account.

    Better to define an enumerated type that would provide thisinformation

    OOP

    108

  • 7/25/2019 APII 3 OOP

    28/33

    4/22/20

    Enumerated TypesExampleEnum AccountType

    Current

    Savings

    Trading

    Annuity

    End Enum

    The enumerated typedefines, and thereforerestricts, the set ofvalues that can beassigned to variablesof its type.

    Internally, the list ofAccountType valuesareassigned the integervalues0, 1, 2, and 3.

    OOP

    109

    Enumerated Types

    When you press the dot after an Enum variable,Visual Studios Intellisense tool showsa list of all theEnumvaluesthe variable can hold.

    Youdo not use the Newkeyword when declaring anenumeratedobject:

    Dim acct As AccountType

    If you declare an AccountType object, only valuesfromthe prescribed list should be assigned to it:

    acct = AccountType.Current

    acct = AccountType.TradingOOP

    110

    Enumerated Types

    The following statement is i llegal because integers are not assignment-compatible withEnum types:

    acct = 1

    In special cases, you can assign an integer into an AccountType, but youshould dothat only when noother optionis available.

    E.g., suppose you were to read an integer from a TextBox, and the integer wassupposed to indicate a type of account.

    TheCtypefunctionmust be used to cast theinteger intoAccountType:

    Dim acct As AccountType

    Dim N As Integer = CInt(txtAccountType.Text)

    acct = CType(N, AccountType) No cast is required to assign an enumerated type to an integer:

    Dim N As Integer = acct

    OOP

    111

    Using Boolean Expressions

    Enumerated types are particularly useful when usedin Boolean expressionsthat involve comparisons.

    Example1

    To take a particular action if an account is an annuity:If acct = AccountType.Annuity Then

    taxDeferred = True

    End If

    Sucha statement iseasier to read than:

    If acctCode = 3 Then

    taxDeferred = True

    End IfOOP

    112

  • 7/25/2019 APII 3 OOP

    29/33

    4/22/20

    Using Boolean Expressions

    Example2

    TheSelect Casestatement can go through a list ofenumerated values and take a separate action foreachpossible value:

    Select Case acct

    Case AccountType.Annuity

    lblResult.Text = "Plan payments for retirement"

    Case AccountType.Checking

    lblResult.Text = "Write checks to pay bills"

    ' etc.

    End Select OOP

    113

    Do Labs:

    1-3: Enumerated Types

    1-4: Bank Teller Application

    Lab114

    OOP

    Lab 1-3

    Enumerated Account type

    When the user selects an account type f rom a list box,the selected index is converted into an AccountTypeobject.

    OOP

    115

    1.4Bank Teller Application

    Two-tier application that simulates an electronicbankteller

    user looks up account, deposits & withdraws funds,viewsthebalance

    OOP

    116

  • 7/25/2019 APII 3 OOP

    30/33

    4/22/20

    Requirements

    1. User looks up existing account information byentering an Account number (ID).

    2. If the account exists, the account name and balanceare displayed.

    3. User can enter an amount to deposit into theaccount. Thisdeposit is added to the balance.

    4. User can enter an amount to withdraw from theaccount. If the amount is

  • 7/25/2019 APII 3 OOP

    31/33

    4/22/20

    Manual Software Testing

    Importance of software testing

    We must create programsthat performin theway they were intended.

    We all like to use reliable software, andoftenour livesdepend on it.For example, the fl ight navigation system for an

    aircraft must not fail, nor should medicaldevices.Search wikipedia for Therac-25, a famous software

    failure. OOP

    121

    Manual Software Testing

    Testing Modes

    Manual testing

    Automated testing

    In manual testing, a human tester manually enters a variety ofinputs into an application.

    The tester compares the actual outcomes produced by thesoftware to a set of expected outcomes.

    Manual testing is often associated with the termblack boxtesting

    where the tester isconcerned only with the programsinput and outputs.

    The tester cannot see the code inside.

    OOP

    122

    Manual Software Testing

    Requires a lot of human labor, and therefore isexpensive.

    Automated testing is performed by a computerprogram, whichexecutespart or all of an applicationin a way that requiresno manual intervention.

    Testingplan

    A list of tests that are run on an application to verifythat the application works asexpected

    For each given user action or input value, the testingplan lists the expected output or action produced bytheapplication. OOP

    123

    Requirements Specification

    Before creating an application, we usually want toknowwhat it issupposed to do.

    A req spec is a complete description of thebehaviour of anapplication

    Used asa guide for software testing

    Describes inputs and actions by the user and outputs,andhow they affect the application'sbehaviour

    In the next slide is a sample requirementsspecification for a program that inputs an integerand displaysa corresponding colour

    OOP

    124

  • 7/25/2019 APII 3 OOP

    32/33

    4/22/20

    Sample RequirementsSpecification

    The application prompts the user with a range of acceptableinteger values.

    The user inputs an integer N.

    If N is a noninteger value, the application displays an errormessage.

    If N is outside the range of acceptable values, the applicationdisplaysan error message.

    If N is within the range of acceptable values, the applicationdisplays the name of a colour that matches N from thefollowing list:

    0 = white,1 = yellow, 2 = green, 3 = red, 4 = blue, 5 = orange.

    OOP

    125

    Do the Lab

    Lab1-5: Manually Testing IntegerInput

    126

    OOP

    Lab 1-5

    Manually testing integer input

    Displays a string by using the input value as asubscript intoan array of strings

    OOP

    127

    Testing Plan

    OOP

    128

  • 7/25/2019 APII 3 OOP

    33/33

    4/22/20

    Key Terms

    accessspecifier

    assignment operator (=)

    attributes

    auto-implemented property

    automated testing

    behaviours

    class

    classdefinition

    classinstance

    class-level variable

    constructor

    data accesstier

    default constructor

    encapsulation principle

    enumerated type

    information hiding principle

    inheritance

    instance

    local variable

    manual testing

    method

    middle tier

    Microsoft .NETFramework

    namespace

    New operator

    object

    object behaviours

    OOP

    129

    More Key Terms

    ob ject initializer

    object-oriented programming (OOP)

    optional parameter

    parameterisedconstructor

    presentat ion tier

    property

    property procedure

    ReadOnlyproperty

    reference type

    reference variable

    requirementsspecification

    shared property

    side effect

    testing plan

    three-tier application model

    ToString method

    user-defined class

    value type

    OOP

    130