Chapter 8 – Object-Based Programming

Slides:



Advertisements
Similar presentations
Road Map Introduction to object oriented programming. Classes
Advertisements

Summary of text to be covered Create your own class Create and use objects of your own class Control access to object instance variables Use keyword private.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with.
ASP.NET Programming with C# and SQL Server First Edition
Object-Oriented Programming in Visual Basic.NET. Overview Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes.
To define a class in Visual Basic.NET, you can follow this general procedure: 1. Add a class to the project. 2. Provide an appropriate file name for.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Module 7: Object-Oriented Programming in Visual Basic .NET
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Why to Create a Procedure
Chapter 8: Writing Graphical User Interfaces
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2 Base Classes and Derived.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
1 Object-Based Programming Implementing Multiple Classes Class Scope Controlling Access to Members Initializing Class Objects: Constructors Using Overloaded.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. © by Pearson Education, Inc.
CSCI 3327 Visual Basic Chapter 9: Object-Oriented Programming: Classes and Objects UTPA – Fall 2011.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1 Introduction 8.2 Implementing a Time Abstract Data Type with.
VB Classes ISYS 512/812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
Object Oriented Programming
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. © by Pearson Education, Inc.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Object-Oriented Programming: Classes and Objects.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
CompSci 230 S Programming Techniques
Visual Basic Fundamental Concepts
Chapter 11 – Exception Handling
Topic: Classes and Objects
Creating and Using Objects, Exceptions, Strings
A variable is a name for a value stored in memory.
Chapter 8 – Object-Based Programming
Classes and Objects: A Deeper Look
Chapters 9, 10 – Object-Oriented Programming: Inheritance
IS 350 Application Structure
C# Object-Oriented Program
Object-Oriented Programming: Classes and Objects
CIS 200 Test 01 Review.
Chapter 9 – Object-Oriented Programming: Inheritance
Object-Oriented Programming: Classes and Objects
Chapter 5 – Control Structures: Part 2
Object Based Programming
Lecture 22 Inheritance Richard Gesick.
Object-Oriented Programming: Classes and Objects
Tonga Institute of Higher Education
Chapter 8 – Object-Based Programming
Methods.
CS360 Client/Server Programming Using Java
Classes & Objects A deeper Look Chapter 10 & 11
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Chapter 9 Introduction To Classes
Classes and Objects Systems Programming.
Chapter 7 Objects and Classes
Presentation transcript:

Chapter 8 – Object-Based Programming Outline Classes as User Defined Types Value-Types and Reference-Types 8.4   Controlling Access to Members 8.5   Constructors 8.6   Overloaded Constructors 8.7   Properties 8.8   Composition: Objects as Instance Variables of Other Classes 8.9   Using the Me Reference 8.10   Garbage Collection 8.11   Shared Class Members 8.12   Const and ReadOnly Members 8.13   Data Abstraction and Information Hiding 8.15   Namespaces and Assemblies

Classes as User Defined Types (1) (JPF) May be used to represent a user defined type Example: Time data type Syntactically much similar to a module Data and operations on the data are defined together Instance variables Represent the data (internal data structure) of an instance of the type Example: hour, minutes and seconds Instance methods (functions and procedures) Represent operations on instances of the type Example: change the time (procedure), convert to string (function)

Classes as User Defined Types (2) (JPF) Encapsulation (private and public) Encapsulation is a fundamental principle of object orientation Instance variables are usually declared private, so that clients of the class do not have direct access to them (can only have indirect access to them via public methods) Clients of a class do not need to know its internal data structure Advantage: integrity of the data (example: 0<=hour<=23, ...) is completely controlled within the class Advantage: the internal data structure may be changed (example: time as seconds elapsed since a reference point), without affecting the clients of the class (as long as the syntax and semantics of public methods is not changed) Special methods named New (constructors) take care of initializing the instance variables of newly allocated instances (object) of the class Auxiliary internal methods should also be declared private

Classes as User Defined Types (3) (JPF) Objects and variables Instances of a class are called objects An object stores the values of the instance variables A variable of class type holds a reference to an object and not the data (or object) itself This is different from what happens with a primitive type Dim i as Integer = 123 Dim t as CTime = New CTime(10,30, 0) i 123 t1 10 30 0 a variable of type CTime an object of type CTime

Value-Types and Reference-Types (JPF) Primitive types such as Integer are value-types Variables of a value-type contain data Comparison and assignment act on values Reference types Classes (user defined or defined in the .Net class libraries) are reference-types Variable of a reference-type contain references to objects (or Nothing when no object is referenced) Objects are created with New New returns a reference to a newly allocated object The result of New is usually assigned to a variable for later use Comparison and assignment act on references

Value-Types and Reference-Types (JPF) Example Dim t1 as CTime = New CTime(10,30, 0) Dim t2 as CTime = New CTime(10,30, 0) Dim t3 as Ctime = t1 if t1 = t2 .... ' dá FALSE if t1 = t3 ' dá TRUE t3 t1 10 30 0 t2 10 30 0

Class CTime inherits existing pieces of class Object. CTime.vb 1 ' Fig. 8.1: CTime.vb 2 ' Represents time in 24-hour format. 3 4 Class CTime 5 Inherits Object 6 7 ' declare Integer instance values for hour, minute and second 8 Private mHour As Integer ' 0 - 23 9 Private mMinute As Integer ' 0 - 59 10 Private mSecond As Integer ' 0 - 59 11 12 ' Method New is the CTime constructor method, which initializes 13 ' instance variables to zero 14 Public Sub New() 15 SetTime(0, 0, 0) 16 End Sub ' New 17 18 ' set new time value using universal time; 19 ' perform validity checks on data; 20 ' set invalid values to zero 21 Public Sub SetTime(ByVal hourValue As Integer, _ 22 ByVal minuteValue As Integer, ByVal secondValue As Integer) 23 24 ' check if hour is between 0 and 23, then set hour 25 If (hourValue >= 0 AndAlso hourValue < 24) Then 26 mHour = hourValue 27 Else 28 mHour = 0 29 End If 30 Class CTime inherits existing pieces of class Object. CTime.vb Introduces a New constructor and constructors do not return values

31 ' check if minute is between 0 and 59, then set minute 32 If (minuteValue >= 0 AndAlso minuteValue < 60) Then 33 mMinute = minuteValue 34 Else 35 mMinute = 0 36 End If 37 38 ' check if second is between 0 and 59, then set second 39 If (secondValue >= 0 AndAlso secondValue < 60) Then 40 mSecond = secondValue 41 Else 42 mSecond = 0 43 End If 44 45 End Sub ' SetTime 46 47 ' convert String to universal-time format 48 Public Function ToUniversalString() As String 49 Return String.Format("{0}:{1:D2}:{2:D2}", _ 50 mHour, mMinute, mSecond) 51 End Function ' ToUniversalString 52 53 ' convert to String in standard-time format 54 Public Function ToStandardString() As String 55 Dim suffix As String = " PM" 56 Dim format As String = "{0}:{1:D2}:{2:D2}" 57 Dim standardHour As Integer 58 59 ' determine whether time is AM or PM 60 If mHour < 12 Then 61 suffix = " AM" 62 End If 63 Error checks input values for variables hourValue, minuteValue and secondValue CTime.vb Argument 0 takes default value zero Arguments 1 and 2 take decimal number format

64 ' convert from universal-time format to standard-time format 65 If (mHour = 12 OrElse mHour = 0) Then 66 standardHour = 12 67 Else 68 standardHour = mHour Mod 12 69 End If 70 71 Return String.Format(format, standardHour, mMinute, _ 72 mSecond) & suffix 73 End Function ' ToStandardString 74 75 End Class ' CTime CTime.vb

TimeTest.vb 1 ' Fig. 8.2: TimeTest.vb 2 ' Demonstrating class CTime. 3 4 Imports System.Windows.Forms ' para não ter de fazer System.Windows.Forms.MessageBox 5 6 Module modTimeTest 7 8 Sub Main() 9 Dim time As CTime = New CTime() ' call CTime constructor 10 Dim output As String 11 12 output = "The initial universal times is: " & _ 13 time.ToUniversalString() & vbCrLf & _ 14 "The initial standard time is: " & _ 15 time.ToStandardString() 16 17 time.SetTime(13, 27, 6) ' set time with valid settings 18 19 output &= vbCrLf & vbCrLf & _ 20 "Universal time after setTime is: " & _ 21 time.ToUniversalString() & vbCrLf & _ 22 "Standard time after setTime is: " & _ 23 time.ToStandardString() 24 25 time.SetTime(99, 99, 99) ' set time with invalid settings 26 27 output &= vbCrLf & vbCrLf & _ 28 "After attempting invalid settings: " & vbCrLf & _ 29 "Universal time: " & time.ToUniversalString() & _ 30 vbCrLf & "Standard time: " & time.ToStandardString() 31 32 MessageBox.Show(output, "Testing Class CTime") 33 End Sub ' Main 34 35 End Module ' modTimeTest TimeTest.vb

TimeTest.vb

8.4 Controlling Access to Members Public versus Private Control access to a class’s instance variables and methods Public Serve primarily to present interfaces of a class Private Holds clients private data safely Get and set functions Have ability to access private data Class members that are visible can be accessed only through a “handle” (ObjectReferenceName.memberName)

Cannot access a Private variable 1 ' Fig. 8.3: RestrictedAccess.vb 2 ' Demonstrate error from attempt to access Private class member. 3 4 Module modRestrictedAccess 5 6 Sub Main() 7 Dim time As New CTime() 8 9 time.mHour = 7 ' error 10 End Sub ' Main 11 12 End Module ' modRestrictedAccess RestrictedAccess.vb Cannot access a Private variable

8.5 Initializing Class Objects: Constructors Initializing Constructors False for Booleans and Nothing for references If an instance variable is not initialized the compiler will assign a default value Form of declarations Dim ObjectReference As New ClassName(arguments) Programs without default constructor are provided with one by the compiler

8.6 Using Overloaded Constructors Must have different numbers and/or types and/or orders of parameters

1 ' Fig. 8.4: CTime2.vb 2 ' Represents time and contains overloaded constructors. 3 4 Class CTime2 5 Inherits Object 6 7 ' declare Integers for hour, minute and second 8 Private mHour As Integer ' 0 - 23 9 Private mMinute As Integer ' 0 - 59 10 Private mSecond As Integer ' 0 - 59 11 12 ' constructor initializes each variable to zero and 13 ' ensures that each CTime2 object starts in consistent state 14 Public Sub New() 15 SetTime() 16 End Sub ' New 17 18 ' CTime2 constructor: hour supplied; 19 ' minute and second default to 0 20 Public Sub New(ByVal hourValue As Integer) 21 SetTime(hourValue) 22 End Sub ' New 23 24 ' CTime2 constructor: hour and minute supplied; 25 ' second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) 28 29 SetTime(hourValue, minuteValue) 30 End Sub ' New 31 32 ' CTime2 constructor: hour, minute and second supplied 33 Public Sub New(ByVal hourValue As Integer, _ 34 ByVal minuteValue As Integer, ByVal secondValue As Integer) 35 CTime2.vb

CTime2.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New 38 39 ' CTime2 constructor: another CTime2 object supplied 40 Public Sub New(ByVal timeValue As CTime2) 41 SetTime(timeValue.mHour, timeValue.mMinute, timeValue.mSecond) 42 End Sub ' New 43 44 ' set new time value using universal time; 45 ' perform validity checks on data; 46 ' set invalid values to zero 47 Public Sub SetTime(Optional ByVal hourValue As Integer = 0, _ 48 Optional ByVal minuteValue As Integer = 0, _ 49 Optional ByVal secondValue As Integer = 0) 50 51 ' perform validity checks on hour, then set hour 52 If (hourValue >= 0 AndAlso hourValue < 24) Then 53 mHour = hourValue 54 Else 55 mHour = 0 56 End If 57 58 ' perform validity checks on minute, then set minute 59 If (minuteValue >= 0 AndAlso minuteValue < 60) Then 60 mMinute = minuteValue 61 Else 62 mMinute = 0 63 End If 64 65 ' perform validity checks on second, then set second 66 If (secondValue >= 0 AndAlso secondValue < 60) Then 67 mSecond = secondValue 68 Else 69 mSecond = 0 70 End If CTime2.vb

CTime2.vb 71 72 End Sub ' SetTime 73 74 ' convert String to universal-time format 75 Public Function ToUniversalString() As String 76 Return String.Format("{0}:{1:D2}:{2:D2}", _ 77 mHour, mMinute, mSecond) 78 End Function ' ToUniversalString 79 80 ' convert to String in standard-time format 81 Public Function ToStandardString() As String 82 Dim suffix As String = " PM" 83 Dim format As String = "{0}:{1:D2}:{2:D2}" 84 Dim standardHour As Integer 85 86 ' determine whether time is AM or PM 87 If mHour < 12 Then 88 suffix = " AM" 89 End If 90 91 ' convert from universal-time format to standard-time format 92 If (mHour = 12 OrElse mHour = 0) Then 93 standardHour = 12 94 Else 95 standardHour = mHour Mod 12 96 End If 97 98 Return String.Format(format, standardHour, mMinute, _ 99 mSecond) & suffix 100 End Function ' ToStandardString 101 102 End Class ' CTime2 CTime2.vb

TimeTest2.vb 1 ' Fig. 8.5: TimeTest2.vb 2 ' Demonstrates overloading constructors. 3 4 Imports System.Windows.Forms 5 6 Module modTimeTest2 7 8 Sub Main() 9 10 ' use overloaded constructors 11 Dim time1 As New CTime2() 12 Dim time2 As New CTime2(2) 13 Dim time3 As New CTime2(21, 34) 14 Dim time4 As New CTime2(12, 25, 42) 15 Dim time5 As New CTime2(27, 74, 99) 16 Dim time6 As New CTime2(time4) ' use time4 as initial value 17 18 Const SPACING As Integer = 13 ' spacing between output text 19 20 ' invoke time1 methods 21 Dim output As String = "Constructed with: " & vbCrLf & _ 22 " time1: all arguments defaulted" & vbCrLf & _ 23 Space(SPACING) & time1.ToUniversalString() & _ 24 vbCrLf & Space(SPACING) & time1.ToStandardString() 25 26 ' invoke time2 methods 27 output &= vbCrLf & _ 28 " time2: hour specified; minute and second defaulted" & _ 29 vbCrLf & Space(SPACING) & _ 30 time2.ToUniversalString() & vbCrLf & Space(SPACING) & _ 31 time2.ToStandardString() 32 TimeTest2.vb

TimeTest2.vb 33 ' invoke time3 methods 34 output &= vbCrLf & _ 35 " time3: hour and minute specified; second defaulted" & _ 36 vbCrLf & Space(SPACING) & time3.ToUniversalString() & _ 37 vbCrLf & Space(SPACING) & time3.ToStandardString() 38 39 ' invoke time4 methods 40 output &= vbCrLf & _ 41 " time4: hour, minute and second specified" & _ 42 vbCrLf & Space(SPACING) & time4.ToUniversalString() & _ 43 vbCrLf & Space(SPACING) & time4.ToStandardString() 44 45 ' invoke time5 methods 46 output &= vbCrLf & _ 47 " time5: hour, minute and second specified" & _ 48 vbCrLf & Space(SPACING) & time5.ToUniversalString() & _ 49 vbCrLf & Space(SPACING) & time5.ToStandardString() 50 51 ' invoke time6 methods 52 output &= vbCrLf & _ 53 " time6: Time2 object time4 specified" & vbCrLf & _ 54 Space(SPACING) & time6.ToUniversalString() & _ 55 vbCrLf & Space(SPACING) & time6.ToStandardString() 56 57 MessageBox.Show(output, _ 58 "Demonstrating Overloaded Constructor") 59 End Sub ' Main 60 61 End Module ' modTimeTest2 TimeTest2.vb

TimeTest2.vb

8.7 Properties Private and Public Get accessor Set accessor In Visual Basic instance variables as private does not guarantee data integrity Set accessor Cannot return values indicating a failed attempt to assign invalid data to objects of the class Control the setting of instance variables to valid values Get and Set accessors are not required A property with only Get accessor is called ReadOnly A property with only Set accessor is called WriteOnly

1 ' Fig. 8.6: CTime3.vb 2 ' Represents time in 24-hour format and contains properties. 3 4 Class CTime3 5 Inherits Object 6 7 ' declare Integers for hour, minute and second 8 Private mHour As Integer 9 Private mMinute As Integer 10 Private mSecond As Integer 11 12 ' CTime3 constructor: initialize each instance variable to zero 13 ' and ensure that each CTime3 object starts in consistent state 14 Public Sub New() 15 SetTime(0, 0, 0) 16 End Sub ' New 17 18 ' CTime3 constructor: 19 ' hour supplied, minute and second defaulted to 0 20 Public Sub New(ByVal hourValue As Integer) 21 SetTime(hourValue, 0, 0) 22 End Sub ' New 23 24 ' CTime3 constructor: 25 ' hour and minute supplied; second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) 28 29 SetTime(hourValue, minuteValue, 0) 30 End Sub ' New 31 32 ' CTime3 constructor: hour, minute and second supplied 33 Public Sub New(ByVal hourValue As Integer, _ 34 ByVal minuteValue As Integer, ByVal secondValue As Integer) 35 CTime3.vb

CTime3.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New 38 39 ' CTime3 constructor: another CTime3 object supplied 40 Public Sub New(ByVal timeValue As CTime3) 41 SetTime(timeValue.mHour, timeValue.mMinute, _ 42 timeValue.mSecond) 43 End Sub ' New 44 45 ' set new time value using universal time; 46 ' uses properties to perform validity checks on data 47 Public Sub SetTime(ByVal hourValue As Integer, _ 48 ByVal minuteValue As Integer, ByVal secondValue As Integer) 49 50 Hour = hourValue ' looks 51 Minute = minuteValue ' dangerous 52 Second = secondValue ' but it is correct 53 End Sub ' SetTime 54 55 ' property Hour 56 Public Property Hour() As Integer 57 58 ' return mHour value 59 Get 60 Return mHour 61 End Get 62 63 ' set mHour value 64 Set(ByVal value As Integer) 65 66 If (value >= 0 AndAlso value < 24) Then 67 mHour = value 68 Else 69 mHour = 0 70 End If CTime3.vb

CTime3.vb 71 72 End Set 73 74 End Property ' Hour 75 76 ' property Minute 77 Public Property Minute() As Integer 78 79 ' return mMinute value 80 Get 81 Return mMinute 82 End Get 83 84 ' set mMinute value 85 Set(ByVal value As Integer) 86 87 If (value >= 0 AndAlso value < 60) Then 88 mMinute = value 89 Else 90 mMinute = 0 91 End If 92 93 End Set 94 95 End Property ' Minute 96 97 ' property Second 98 Public Property Second() As Integer 99 100 ' return mSecond value 101 Get 102 Return mSecond 103 End Get 104 CTime3.vb

CTime3.vb 105 ' set mSecond value 106 Set(ByVal value As Integer) 107 108 If (value >= 0 AndAlso value < 60) Then 109 mSecond = value 110 Else 111 mSecond = 0 112 End If 113 114 End Set 115 116 End Property ' Second 117 118 ' convert String to universal-time format 119 Public Function ToUniversalString() As String 120 Return String.Format("{0}:{1:D2}:{2:D2}", _ 121 mHour, mMinute, mSecond) 122 End Function ' ToUniversalString 123 124 ' convert to String in standard-time format 125 Public Function ToStandardString() As String 126 Dim suffix As String = " PM" 127 Dim format As String = "{0}:{1:D2}:{2:D2}" 128 Dim standardHour As Integer 129 130 ' determine whether time is AM or PM 131 If mHour < 12 Then 132 suffix = " AM" 133 End If 134 CTime3.vb

135 ' convert from universal-time format to standard-time format 136 If (mHour = 12 OrElse mHour = 0) Then 137 standardHour = 12 138 Else 139 standardHour = mHour Mod 12 140 End If 141 142 Return String.Format(format, standardHour, mMinute, _ 143 mSecond) & suffix 144 End Function ' ToStandardString 145 146 End Class ' CTime3 CTime3.vb

TimeTest3.vb 1 ' Fig. 8.7: TimeTest3.vb 2 ' Demonstrates Properties. 3 4 Imports System.Windows.Forms 5 6 Class FrmTimeTest3 7 Inherits Form 8 9 ' Label and TextBox for hour 10 Friend WithEvents lblSetHour As Label 11 Friend WithEvents txtSetHour As TextBox 12 13 ' Label and TextBox for minute 14 Friend WithEvents lblSetMinute As Label 15 Friend WithEvents txtSetMinute As TextBox 16 17 ' Label and TextBox for second 18 Friend WithEvents lblSetSecond As Label 19 Friend WithEvents txtSetSecond As TextBox 20 21 ' Labels for outputting time 22 Friend WithEvents lblOutput1 As Label 23 Friend WithEvents lblOutput2 As Label 24 25 ' Button for adding one second to time 26 Friend WithEvents cmdAddSecond As Button 27 28 Dim time As New CTime3() 29 30 ' Visual Studio .NET generated code 31 TimeTest3.vb

TimeTest3.vb 32 ' update time display 33 Private Sub UpdateDisplay() 34 lblOutput1.Text = "Hour: " & time.Hour & "; Minute: " & _ 35 time.Minute & "; Second: " & time.Second 36 37 lblOutput2.Text = "Standard time is: " & _ 38 time.ToStandardString & "; Universal Time is: " _ 39 & time.ToUniversalString() 40 End Sub ' UpdateDisplay 41 42 ' invoked when user presses Add Second button 43 Protected Sub cmdAddSecond_Click( _ 44 ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdAddSecond.Click 46 47 ' add one second 48 time.Second = (time.Second + 1) Mod 60 49 txtSetSecond.Text = time.Second 50 51 ' add one minute if 60 seconds have passed 52 If time.Second = 0 Then 53 time.Minute = (time.Minute + 1) Mod 60 54 txtSetMinute.Text = time.Minute 55 56 ' add one hour if 60 minutes have passed 57 If time.Minute = 0 Then 58 time.Hour = (time.Hour + 1) Mod 24 59 txtSetHour.Text = time.Hour 60 End If 61 62 End If 63 64 UpdateDisplay() 65 End Sub ' cmdAddSecond_Click 66 TimeTest3.vb

TimeTest3.vb 67 ' handle event when txtSetHour's text changes 68 Protected Sub txtSetHour_TextChanged(ByVal sender As _ 69 System.Object, ByVal e As System.EventArgs) _ 70 Handles txtSetHour.TextChanged 71 72 time.Hour = Convert.ToInt32(txtSetHour.Text) 73 UpdateDisplay() 74 End Sub ' txtSetHour_TextChanged 75 76 ' handle event when txtSetMinute's text changes 77 Protected Sub txtSetMinute_TextChanged(ByVal sender As _ 78 System.Object, ByVal e As System.EventArgs) _ 79 Handles txtSetMinute.TextChanged 80 81 time.Minute = Convert.ToInt32(txtSetMinute.Text) 82 UpdateDisplay() 83 End Sub ' txtSetMinute_TextChanged 84 85 ' handle event when txtSetSecond's text changes 86 Protected Sub txtSetSecond_TextChanged(ByVal sender _ 87 As System.Object, ByVal e As System.EventArgs) _ 88 Handles txtSetSecond.TextChanged 89 90 time.Second = Convert.ToInt32(txtSetSecond.Text) 91 UpdateDisplay() 92 End Sub ' txtSetSecond_TextChanged 93 94 End Class ' FrmTimeTest3 TimeTest3.vb

TimeTest3.vb

8.8 Composition: Objects as Instance Variables of Other Classes Referencing Existing Objects Software Reuse: A form of composition is software reuse

CDay.vb 1 ' Fig. 8.8: CDay.vb 2 ' Encapsulates month, day and year. 3 4 Imports System.Windows.Forms 5 6 Class CDay 7 Inherits Object 8 9 Private mMonth As Integer ' 1-12 10 Private mDay As Integer ' 1-31 based on month 11 Private mYear As Integer ' any year 12 13 ' constructor confirms proper value for month, then calls 14 ' method CheckDay to confirm proper value for day 15 Public Sub New(ByVal monthValue As Integer, _ 16 ByVal dayValue As Integer, ByVal yearValue As Integer) 17 18 ' ensure month value is valid 19 If (monthValue > 0 AndAlso monthValue <= 12) Then 20 mMonth = monthValue 21 Else 22 mMonth = 1 23 24 ' inform user of error 25 Dim errorMessage As String = _ 26 "Month invalid. Set to month 1." 27 28 MessageBox.Show(errorMessage, "", _ 29 MessageBoxButtons.OK, MessageBoxIcon.Error) 30 End If 31 32 mYear = yearValue 33 mDay = CheckDay(dayValue) ' validate day 34 35 End Sub ' New CDay.vb

CDay.vb 36 37 ' confirm proper day value based on month and year 38 Private Function CheckDay(ByVal testDayValue As Integer) _ 39 As Integer 40 41 Dim daysPerMonth() As Integer = _ 42 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 43 44 If (testDayValue > 0 AndAlso _ 45 testDayValue <= daysPerMonth(mMonth)) Then 46 47 Return testDayValue 48 End If 49 50 ' check for leap year in February 51 If (mMonth = 2 AndAlso testDayValue = 29 AndAlso _ 52 mYear Mod 400 = 0 OrElse mYear Mod 4 = 0 AndAlso _ 53 mYear Mod 100 <> 0) Then 54 55 Return testDayValue 56 Else 57 58 ' inform user of error 59 Dim errorMessage As String = _ 60 "day " & testDayValue & "invalid. Set to day 1. " 61 62 MessageBox.Show(errorMessage, "", _ 63 MessageBoxButtons.OK, MessageBoxIcon.Error) 64 65 Return 1 ' leave object in consistent state 66 End If 67 68 End Function ' CheckDay 69 CDay.vb

CDay.vb 70 ' create string containing month/day/year format 71 Public Function ToStandardString() As String 72 Return mMonth & "/" & mDay & "/" & mYear 73 End Function ' ToStandardString 74 75 End Class ' CDay CDay.vb

CEmployee.vb 1 ' Fig. 8.9: CEmployee.vb 2 ' Represent employee name, birthday and hire date. 3 4 Class CEmployee 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 Private mBirthDate As CDay ' member object reference 10 Private mHireDate As CDay ' member object reference 11 12 ' CEmployee constructor 13 Public Sub New(ByVal firstNameValue As String, _ 14 ByVal lastNameValue As String, _ 15 ByVal birthMonthValue As Integer, _ 16 ByVal birthDayValue As Integer, _ 17 ByVal birthYearValue As Integer, _ 18 ByVal hireMonthValue As Integer, _ 19 ByVal hireDayValue As Integer, _ 20 ByVal hireYearValue As Integer) 21 22 mFirstName = firstNameValue 23 mLastName = lastNameValue 24 25 ' create CDay instance for employee birthday 26 mBirthDate = New CDay(birthMonthValue, birthDayValue, _ 27 birthYearValue) 28 29 ' create CDay instance for employee hire date 30 mHireDate = New CDay(hireMonthValue, hireDayValue, _ 31 hireYearValue) 32 End Sub ' New 33 CEmployee.vb

34 ' return employee information as standard-format String 35 Public Function ToStandardString() As String 36 Return mLastName & ", " & mFirstName & " Hired: " _ 37 & mHireDate.ToStandardString() & " Birthday: " & _ 38 mBirthDate.ToStandardString() 39 End Function ' ToStandardString 40 41 End Class ' CEmployee CEmployee.vb

CompositionTest.vb 1 ' Fig. 8.10: CompositionTest.vb 2 ' Demonstrate an object with member object reference. 3 4 Imports System.Windows.Forms 5 6 Module modCompositionTest 7 8 Sub Main() 9 Dim employee As New CEmployee( _ 10 "Bob", "Jones", 7, 24, 1949, 3, 12, 1988) 11 12 MessageBox.Show(employee.ToStandardString(), _ 13 "Testing Class Employee") 14 End Sub ' Main 15 16 End Module ' modCompositionTest CompositionTest.vb

8.9 Using the Me Reference Me Reference Every object can access a reference to itself using a Me reference. Me explicitly Me implicitly The explicit use of the Me reference can increase program clarity where Me is optional

Reference Me can refer to any instance variable explicitly 1 ' Fig. 8.11: CTime4.vb 2 ' Encapsulate time using Me reference. 3 4 Class CTime4 5 Private mHour, mMinute, mSecond As Integer 6 7 ' CTime4 constructor 8 Public Sub New(ByVal mHour As Integer, _ 9 ByVal mMinute As Integer, ByVal mSecond As Integer) 10 11 Me.mHour = mHour 12 Me.mMinute = mMinute 13 Me.mSecond = mSecond 14 End Sub ' New 15 16 ' create String using Me and implicit references 17 Public Function BuildString() As String 18 Return "Me.ToUniversalString(): " & Me.ToUniversalString() _ 19 & vbCrLf & "ToUniversalString(): " & ToUniversalString() 20 End Function ' BuildString 21 22 ' convert to String in standard-time format 23 Public Function ToUniversalString() As String 24 Return String.Format("{0:D2}:{1:D2}:{2:D2}", _ 25 mHour, mMinute, mSecond) 26 End Function ' ToUniversalString 27 28 End Class ' CTime4 CTime4.vb Reference Me can refer to any instance variable explicitly Uses reference Me explicitly Uses reference Me implicitly

MeTest.vb 1 ' Fig. 8.12: MeTest.vb 2 ' Demonstrates Me reference. 3 4 Imports System.Windows.Forms 5 6 Module modMeTest 7 8 Sub Main() 9 Dim time As New CTime4(12, 30, 19) 10 11 MessageBox.Show(time.BuildString(), _ 12 "Demonstrating the 'Me' Reference") 13 End Sub ' Main 14 15 End Module ' modMeTest MeTest.vb

* Finalizer methods Finalizer method performs termination housekeeping on that object just before the garbage collector reclaims the object's memory.

Accessed with ClassName.SharedMemberName 8.11 Shared Class Members Shared Class Variable Contains only one copy of this variable in memory When a single copy of the data will suffice, use Shared class variables to save storage. Shared class variables are not the same as global variables because Shared class variables have class scope Shared Class Method have no Me reference Accessed with ClassName.SharedMemberName

Initializes mCount to 0 by default 1 ' Fig. 8.13: CEmployee2.vb 2 ' Class CEmployee2 uses Shared variable. 3 4 Class CEmployee2 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 10 ' number of objects in memory 11 Private Shared mCount As Integer 12 13 ' CEmployee2 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) 16 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New 25 26 ' finalizer method decrements Shared count of employees 27 Protected Overrides Sub Finalize() 28 mCount -= 1 ' decrement mCount, resulting in one fewer object 29 Console.WriteLine _ 30 ("Employee object finalizer: " & mFirstName & _ 31 " " & mLastName & "; count = " & mCount) 32 End Sub ' Finalize 33 CEmployee2.vb Initializes mCount to 0 by default CEmployee2 constructor increments mCount Finalize method decrements mCount

Member mCount can be referenced without declaring a CEmployee2 object 34 ' return first name 35 Public ReadOnly Property FirstName() As String 36 37 Get 38 Return mFirstName 39 End Get 40 41 End Property ' FirstName 42 43 ' return last name 44 Public ReadOnly Property LastName() As String 45 46 Get 47 Return mLastName 48 End Get 49 50 End Property ' LastName 51 52 ' property Count 53 Public ReadOnly Shared Property Count() As Integer 54 55 Get 56 Return mCount 57 End Get 58 59 End Property ' Count 60 61 End Class ' CEmployee2 CEmployee2.vb Member mCount can be referenced without declaring a CEmployee2 object

Sets objects’ references to Nothing 1 ' Fig. 8.14: SharedTest.vb 2 ' Demonstrates Shared members. 3 4 Imports System.Windows.Forms 5 6 Module modSharedTest 7 8 Sub Main() 9 Dim output As String 10 11 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee2.Count) 13 14 Dim employee1 As CEmployee2 = _ 15 New CEmployee2("Susan", "Baker") 16 17 Dim employee2 As CEmployee2 = _ 18 New CEmployee2("Bob", "Jones") 19 20 ' output of employee2 after instantiation 21 Console.WriteLine(vbCrLf & _ 22 "Employees after instantiation: " & vbCrLf & _ 23 "via Employee.Count: " & CEmployee2.Count) 24 25 ' display name of first and second employee 26 Console.WriteLine(vbCrLf & "Employees 1: " & _ 27 employee1.FirstName & " " & employee1.LastName & _ 28 vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ 29 employee2.LastName) 30 31 ' mark employee1 and employee2 for garbage collection 32 employee1 = Nothing 33 employee2 = Nothing 34 SharedTest.vb Declares two CEmployee2 objects and increments mCount by two Sets objects’ references to Nothing

SharedTest.vb 35 System.GC.Collect() ' request garbage collection 36 End Sub ' Main 37 38 End Module ' modShared SharedTest.vb Employees before instantiation: 0 Employee object constructor: Susan Baker Employee object constructor: Bob Jones   Employees after instantiation: via Employee.Count: 2 Employees 1: Susan Baker Employee 2: Bob Jones Employee object finalizer: Bob Jones; count = 1 Employee object finalizer: Susan Baker; count = 0

8.12 Const and ReadOnly Members Const or ReadOnly Const A data member must be initialized in its declaration Cannot be modified once initialized ReadOnly A data member can be initialized either in the class structure or in its declaration

CCircleConstants.vb 1 ' Fig. 8.15: CCircleConstants.vb 2 ' Encapsulate constants PI and radius. 3 4 Class CCircleConstants 5 6 ' PI is constant data member 7 Public Const PI As Double = 3.14159 8 9 ' radius is uninitialized constant 10 Public ReadOnly RADIUS As Integer 11 12 ' constructor of class CCircleConstants 13 Public Sub New(ByVal radiusValue As Integer) 14 RADIUS = radiusValue 15 End Sub ' New 16 17 End Class ' CCircleConstants CCircleConstants.vb

ConstAndReadOnly.vb 1 ' Fig. 8.16: ConstAndReadOnly.vb 2 ' Demonstrates Const and ReadOnly members. 3 4 Imports System.Windows.Forms 5 6 Module modConstAndReadOnly 7 8 Sub Main() 9 Dim random As Random = New Random() 10 Dim circle As CCircleConstants = _ 11 New CCircleConstants(random.Next(1, 20)) 12 13 Dim radius As String = Convert.ToString(circle.RADIUS) 14 15 Dim output As String = "Radius = " & radius & vbCrLf _ 16 & "Circumference = " + String.Format("{0:N3}", _ 17 circle.RADIUS * 2 * CCircleConstants.PI) 18 19 MessageBox.Show(output, "Circumference", _ 20 MessageBoxButtons.OK, MessageBoxIcon.Information) 21 End Sub ' Main 22 23 End Module ' modConstAndReadOnly ConstAndReadOnly.vb

8.15 Namespaces and Assemblies .NET Framework Class Library .NET Framework: Must be imported to a Visual Basic program by including a reference to those libraries Namespaces: Namespaces help minimize naming collisions by proving a convention for unique class names By default, every executable file you create with Visual Basic .NET contains a namespace with the same name as your project. For example, if you define an object within a project named ListBoxProject, the executable file, ListBoxProject.exe, contains a namespace called ListBoxProject. If you use the Imports statement without an alias, you can use all the names in that namespace without qualification provided they are unique to the project.

CEmployee3.vb 1 ' Fig. 8.17: CEmployee3.vb 2 ' Class CEmployee3 uses Shared variable. 3 4 Public Class CEmployee3 5 Inherits Object 6 7 Private mFirstName As String 8 Private mLastName As String 9 10 ' number of objects in memory 11 Private Shared mCount As Integer 12 13 ' CEmployee3 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) 16 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New 25 26 ' finalizer method decrements Shared count of employees 27 Protected Overrides Sub Finalize() 28 mCount -= 1 ' decrement mCount, resulting in one fewer object 29 Console.WriteLine _ 30 ("Employee object finalizer: " & mFirstName & _ 31 " " & mLastName & "; count = " & mCount) 32 End Sub ' Finalize 33 CEmployee3.vb

CEmployee3.vb 34 ' return first name 35 Public ReadOnly Property FirstName() As String 36 37 Get 38 Return mFirstName 39 End Get 40 41 End Property ' FirstName 42 43 ' return last name 44 Public ReadOnly Property LastName() As String 45 46 Get 47 Return mLastName 48 End Get 49 50 End Property ' LastName 51 52 ' property Count 53 Public ReadOnly Shared Property Count() As Integer 54 55 Get 56 Return mCount 57 End Get 58 59 End Property ' Count 60 61 End Class ' CEmployee3 CEmployee3.vb

8.15 Namespaces Fig. 8.18 Simple Class Library.

The module imports class CEmployee3 1 ' Fig. 8.19: AssemblyTest.vb 2 ' Demonstrates assembly files and namespaces. 3 4 Imports EmployeeLibrary ' contains class CEmployee3 5 6 Module modAssemblyTest 7 8 Public Sub Main() 9 Dim output As String 10 11 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee3.Count) 13 14 Dim employee1 As CEmployee3 = _ 15 New CEmployee3("Susan", "Baker") 16 17 Dim employee2 As CEmployee3 = _ 18 New CEmployee3("Bob", "Jones") 19 20 ' output of employee after instantiation 21 Console.WriteLine(vbCrLf & "Employees after instantiation:" _ 22 & vbCrLf & "via Employee.Count: " & CEmployee3.Count) 23 24 ' display name of first and second employee 25 Console.WriteLine(vbCrLf & "Employees 1: " & _ 26 employee1.FirstName & " " & employee1.LastName & _ 27 vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ 28 employee2.LastName) 29 30 ' mark employee1 and employee2 for garbage collection 31 employee1 = Nothing 32 employee2 = Nothing 33 AssemblyTest.vb The module imports class CEmployee3

AssemblyTest.vb 34 System.GC.Collect() ' request garbage collection 35 End Sub ' Main 36 37 End Module ' modAssemblyTest AssemblyTest.vb Employees before instantiation: 0 Employee object constructor: Susan Baker Employee object constructor: Bob Jones   Employees after instantiation: via Employee.Count: 2 Employees 1: Susan Baker Employee 2: Bob Jones Employee object finalizer: Bob Jones; count = 1 Employee object finalizer: Susan Baker; count = 0

* 8.16 Class View and Object Browser Displays a project’s class members To access this feature select VIEW>CLASS VIEW (+) node called collapsed (-) node is called expanded Object Browser Lists the Framework Class Library Available in Visual Basic To access this feature, right click any Visual Basic class or method in the code editor and select Go To Definition It illustrates the functionally provided by a specific object

8.16 Class View and Object Browser Fig. 8.20 Class View of Fig. 8.1 and Fig. 8.2.

8.16 Class View and Object Browser Fig. 8.21 Object Browser when user selects Object from CTime.vb,

8.16 Class View and Object Browser Fig. 8.21 Object Browser when user selects Object from CTime.vb,

Classes as Real World Concepts (JPF) Examples in a banking application: Customer holds data about a customer (number, name, address, ...) provides operations on customers (create, update the address, query accounts, ...) Account holds data about an account (number, owners, movements, balance, ...) provides operations on accounts (create, deposit, withdrawal, query movements, query balance, query owners, ...) Related with each other