 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with.

Slides:



Advertisements
Similar presentations
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
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 Object Oriented Programming Revisited Object Orientation –Classes Encapsulate data –Attributes Encapsulate.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
Introduction to Classes and Data Abstraction
Chapter 11: Classes and Data Abstraction
ASP.NET Programming with C# and SQL Server First Edition
VB Classes ISYS 512. Adding a Class to a Project Project/Add Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in.
Review of C++ Programming Part II Sheng-Fang Huang.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
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.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2 Base Classes and Derived.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
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.
CS0004: Introduction to Programming Project 1 – Lessons Learned.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
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.
Chapter 9 Classes: A Deeper Look, Part I Part II.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 23 November 19, 2009.
 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.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
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.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
 2002 Prentice Hall. All rights reserved. 1 Week 4: OOP Questions from last lecture: –Single-subscript arrays –Multiple-subscript arrays –Homework/Practical.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
 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.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 8 – Object-Based Programming Part II 8.9 Composition 8.10 Garbage Collection 8.11 Static Class.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Chapter 8 – Object-Based Programming
Classes and Objects: A Deeper Look
Chapter 8 – Object-Based Programming
Object-Oriented Programming: Classes and Objects
Chapter 16: Classes and Data Abstraction
Chapter 3: Using Methods, Classes, and Objects
Object-Oriented Programming: Classes and Objects
Object Based Programming
Lecture 22 Inheritance Richard Gesick.
Object-Oriented Programming: Classes and Objects
Tonga Institute of Higher Education
Chapter 8 – Object-Based Programming
CS360 Client/Server Programming Using Java
Classes & Objects A deeper Look Chapter 10 & 11
More C++ Classes Systems Programming.
Presentation transcript:

 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1Introduction 8.2 Implementing a Time Abstract Data Type with a Class 8.3 Class Scope 8.4 Controlling Access to Members 8.5 Initializing Class Objects: Constructors 8.6 Using 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.14 Software Reusability 8.15 Namespaces and Assemblies

 2002 Prentice Hall. All rights reserved Introduction Object Orientation –Requires understanding of : Encapsulation: instance variable(data), methods (behaviors) Information hiding : implementation –Object Programming Class vs. user defined type Object instantiation vs. variable

 2002 Prentice Hall. All rights reserved Implementing a Time Abstract Data type with a Class Abstract Data Types (ADT, i.e. Classes) –Instance variable Object in consistent state Initialize the instance variables Information hiding –Member access modifier Public: accessible whenever the program has a reference to the object Private: accessible only to methods of the class. Private methods are also called utility methods, or helper methods –Normally, instance variable are declared private, methods are declared public. However, it is OK to have private methods and public instance variables. –Predicate method: test the truth of a condition, like IsEmpty –Constructor: a special method to initialize an object’s instance variables, usually New

 2002 Prentice Hall. All rights reserved. Outline 4 CTime.vb Class CTime inherits existing pieces of class Object. 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 ' Private mMinute As Integer ' Private mSecond As Integer ' ' 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 ' 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) ' 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 Introduces a New constructor and constructors do not return values CTime class definition Inherits Object indicates class CTime inherits existing pieces of class Object

 2002 Prentice Hall. All rights reserved. Outline 5 CTime.vb 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 ' 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 End Sub ' SetTime ' 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 ' 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 ' determine whether time is AM or PM 60 If mHour < 12 Then 61 suffix = " AM" 62 End If 63 Argument 0 takes default format Arguments 1 and 2 take decimal number format Error checks input values for variables hourValue, minuteValue and secondValue

 2002 Prentice Hall. All rights reserved. Outline 6 CTime.vb 64 ' convert from universal-time format to standard-time format 65 If (mHour = 12 OrElse mHour = 0) Then 66 standardHour = Else 68 standardHour = mHour Mod End If Return String.Format(format, standardHour, mMinute, _ 72 mSecond) & suffix 73 End Function ' ToStandardString End Class ' CTime Returns standard string from universal string

 2002 Prentice Hall. All rights reserved. Outline 7 TimeTest.vb 1 ' Fig. 8.2: TimeTest.vb 2 ' Demonstrating class CTime. 3 4 Imports System.Windows.Forms 5 6 Module modTimeTest 7 8 Sub Main() 9 Dim time As New CTime() ' call CTime constructor 10 Dim output As String output = "The initial universal times is: " & _ 13 time.ToUniversalString() & vbCrLf & _ 14 "The initial standard time is: " & _ 15 time.ToStandardString() time.SetTime(13, 27, 6) ' set time with valid settings output &= vbCrLf & vbCrLf & _ 20 "Universal time after setTime is: " & _ 21 time.ToUniversalString() & vbCrLf & _ 22 "Standard time after setTime is: " & _ 23 time.ToStandardString() time.SetTime(99, 99, 99) ' set time with invalid settings output &= vbCrLf & vbCrLf & _ 28 "After attempting invalid settings: " & vbCrLf & _ 29 "Universal time: " & time.ToUniversalString() & _ 30 vbCrLf & "Standard time: " & time.ToStandardString() MessageBox.Show(output, "Testing Class CTime") 33 End Sub ' Main End Module ' modTimeTest Invokes method setTime of class CTime and sets each Private instance variable to 0 Declares output as string Assigns time to output then converts To- UniveralString and ToStandardString Demonstrates both formats were set correctly Demonstrates that default values work correctly

 2002 Prentice Hall. All rights reserved. Outline 8 TimeTest.vb

 2002 Prentice Hall. All rights reserved Class Scope Class's Scope –Instance variables and methods Class’s members –Class members that are visible (ex., Public) can be accessed only through a “handle” (ObjectReferenceName.memberName) Variables within methods –Only methods can access that variable If a method defines a variable with the same name as an instance variable, the method-scope variable hides the class- scope variable in that method’s scope. Keyword Me –A hidden instance variable can be accessed in a method by preceding its name with the keyword Me and dot operator

 2002 Prentice Hall. All rights reserved 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 for property Provide ability to access private data safely A Set accessor can provide data validation, and translate between the format of interface data and the format in the implementation A Get accessor can edit the data to limit the client’s view of that data

 2002 Prentice Hall. All rights reserved. Outline 11 RestrictedAccess.vb 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 End Module ' modRestrictedAccess Cannot access a Private variable

 2002 Prentice Hall. All rights reserved Initializing Class Objects: Constructors No return type Initializing Constructors –Invoked each time an object of the class is instantiated –If an instance variable is not initialized the compiler will assign a default value False for Booleans and Nothing for references –Classes can provide overloaded constructors (8.6) –Form of declarations Dim ObjectReference As New ClassName(arguments) Programs without default constructor are provided with one by the compiler, which contains no code and takes no argument

 2002 Prentice Hall. All rights reserved Using Overloaded Constructors Overloaded Constructors –Must have different numbers and/or types and/or orders of parameters –VB runtime will invoke the appropriate constructor by matching the number, types, and order of argument

 2002 Prentice Hall. All rights reserved. Outline 14 CTime2.vb 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 ' Private mMinute As Integer ' Private mSecond As Integer ' ' 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 ' 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 ' CTime2 constructor: hour and minute supplied; 25 ' second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) SetTime(hourValue, minuteValue) 30 End Sub ' New ' 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 Initialize Private variables mHour, mMinute and mSecond to 0 Declares CTime2 constructor with one argument of hourValue Declares CTime2 constructor with two arguments of hourValue and minuteValue Declares CTime2 constructor with three arguments of hourValue, minuteValue secondValue

 2002 Prentice Hall. All rights reserved. Outline 15 CTime2.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New ' 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 ' 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) ' 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 ' 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 ' 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 Values of mHour, mMinute, and mSecond are initialized when supplied Error checks input values for variables hourValue, minuteValue, and secondValue

 2002 Prentice Hall. All rights reserved. Outline 16 CTime2.vb End Sub ' SetTime ' 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 ' 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 ' determine whether time is AM or PM 87 If mHour < 12 Then 88 suffix = " AM" 89 End If ' convert from universal-time format to standard-time format 92 If (mHour = 12 OrElse mHour = 0) Then 93 standardHour = Else 95 standardHour = mHour Mod End If Return String.Format(format, standardHour, mMinute, _ 99 mSecond) & suffix 100 End Function ' ToStandardString End Class ' CTime2 0’s are placed for every missing values to satisfy SetTimes’s requirement

 2002 Prentice Hall. All rights reserved. Outline 17 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 Const SPACING As Integer = 13 ' spacing between output text ' 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() ' 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 Time1 constructor has necessary number of arguments to be invoked Declares six different CTime objects that invoke various constructors of different class

 2002 Prentice Hall. All rights reserved. Outline 18 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() ' 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() ' 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() ' invoke time6 methods 52 output &= vbCrLf & _ 53 " time6: Time2 object time4 specified" & vbCrLf & _ 54 Space(SPACING) & time6.ToUniversalString() & _ 55 vbCrLf & Space(SPACING) & time6.ToStandardString() MessageBox.Show(output, _ 58 "Demonstrating Overloaded Constructor") 59 End Sub ' Main End Module ' modTimeTest2 Shows the output in MessageBox.Show

 2002 Prentice Hall. All rights reserved. Outline 19 TimeTest2.vb

 2002 Prentice Hall. All rights reserved Properties Private and Public –Set accessor In Visual Basic instance variables as private does not guarantee data integrity. Validity checking must be done by programmers. Cannot return values indicating a failed attempt to assign invalid data to objects of the class. This could be done through exception handling (Ch 11). 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, and must be declared using keyword ReadOnly A property with only Set accessor is called WriteOnly, and must be declared using keyword WriteOnly. This is seldom used. – 訂正 : line 5 of p. 314, “or set (i.e. obtain value of)” should be “or get (i.e. obtain value of)”

 2002 Prentice Hall. All rights reserved. Outline 21 CTime3.vb 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 ' 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 ' 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 ' CTime3 constructor: 25 ' hour and minute supplied; second defaulted to 0 26 Public Sub New(ByVal hourValue As Integer, _ 27 ByVal minuteValue As Integer) SetTime(hourValue, minuteValue, 0) 30 End Sub ' New ' 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

 2002 Prentice Hall. All rights reserved. Outline 22 CTime3.vb 36 SetTime(hourValue, minuteValue, secondValue) 37 End Sub ' New ' 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 ' 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) Hour = hourValue ' looks 51 Minute = minuteValue ' dangerous 52 Second = secondValue ' but it is correct 53 End Sub ' SetTime ' property Hour 56 Public Property Hour() As Integer ' return mHour value 59 Get 60 Return mHour 61 End Get ' set mHour value 64 Set(ByVal value As Integer) If (value >= 0 AndAlso value < 24) Then 67 mHour = value 68 Else 69 mHour = 0 70 End If Defines the properties Hour of class CTime3 Error checks bogus input for variable mHour

 2002 Prentice Hall. All rights reserved. Outline 23 CTime3.vb End Set End Property ' Hour ' property Minute 77 Public Property Minute() As Integer ' return mMinute value 80 Get 81 Return mMinute 82 End Get ' set mMinute value 85 Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then 88 mMinute = value 89 Else 90 mMinute = 0 91 End If End Set End Property ' Minute ' property Second 98 Public Property Second() As Integer ' return mSecond value 101 Get 102 Return mSecond 103 End Get 104 Defines the properties for Minute and error checks for erroneous input for variable value Sets variable mMinute to value

 2002 Prentice Hall. All rights reserved. Outline 24 CTime3.vb 105 ' set mSecond value 106 Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then 109 mSecond = value 110 Else 111 mSecond = End If End Set End Property ' Second ' 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 ' 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 ' determine whether time is AM or PM 131 If mHour < 12 Then 132 suffix = " AM" 133 End If 134 Checks for erroneous input for variable value Sets variable mSecond to value

 2002 Prentice Hall. All rights reserved. Outline 25 CTime3.vb 135 ' convert from universal-time format to standard-time format 136 If (mHour = 12 OrElse mHour = 0) Then 137 standardHour = Else 139 standardHour = mHour Mod End If Return String.Format(format, standardHour, mMinute, _ 143 mSecond) & suffix 144 End Function ' ToStandardString End Class ' CTime3

 2002 Prentice Hall. All rights reserved. Outline 26 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 ' Label and TextBox for minute 14 Friend WithEvents lblSetMinute As Label 15 Friend WithEvents txtSetMinute As TextBox ' Label and TextBox for second 18 Friend WithEvents lblSetSecond As Label 19 Friend WithEvents txtSetSecond As TextBox ' Labels for outputting time 22 Friend WithEvents lblOutput1 As Label 23 Friend WithEvents lblOutput2 As Label ' Button for adding one second to time 26 Friend WithEvents cmdAddSecond As Button Dim time As New CTime3() ' Visual Studio.NET generated code 31

 2002 Prentice Hall. All rights reserved. Outline 27 TimeTest3.vb 32 ' update time display 33 Private Sub UpdateDisplay() 34 lblOutput1.Text = "Hour: " & time.Hour & "; Minute: " & _ 35 time.Minute & "; Second: " & time.Second lblOutput2.Text = "Standard time is: " & _ 38 time.ToStandardString & "; Universal Time is: " _ 39 & time.ToUniversalString() 40 End Sub ' UpdateDisplay ' 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 ' add one second 48 time.Second = (time.Second + 1) Mod txtSetSecond.Text = time.Second ' add one minute if 60 seconds have passed 52 If time.Second = 0 Then 53 time.Minute = (time.Minute + 1) Mod txtSetMinute.Text = time.Minute ' add one hour if 60 minutes have passed 57 If time.Minute = 0 Then 58 time.Hour = (time.Hour + 1) Mod txtSetHour.Text = time.Hour 60 End If End If UpdateDisplay() 65 End Sub ' cmdAddSecond_Click 66 The method cmdAddSecond_Click determines and sets the new time

 2002 Prentice Hall. All rights reserved. Outline 28 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 time.Hour = Convert.ToInt32(txtSetHour.Text) 73 UpdateDisplay() 74 End Sub ' txtSetHour_TextChanged ' 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 time.Minute = Convert.ToInt32(txtSetMinute.Text) 82 UpdateDisplay() 83 End Sub ' txtSetMinute_TextChanged ' 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 time.Second = Convert.ToInt32(txtSetSecond.Text) 91 UpdateDisplay() 92 End Sub ' txtSetSecond_TextChanged End Class ' FrmTimeTest3 Declares three methods that use Hour, Minute and Second properties of CTime3 Object to alter time values

 2002 Prentice Hall. All rights reserved. Outline 29 TimeTest3.vb

 2002 Prentice Hall. All rights reserved Composition: Objects as Instance Variables of Other Classes The use of references to objects of preexisting classes as members of new objects is called composition. Referencing Existing Objects –Software Reuse: A form of composition is software reuse

 2002 Prentice Hall. All rights reserved. Outline 31 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 ' Private mDay As Integer ' 1-31 based on month 11 Private mYear As Integer ' any year ' 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) ' ensure month value is valid 19 If (monthValue > 0 AndAlso monthValue <= 12) Then 20 mMonth = monthValue 21 Else 22 mMonth = ' inform user of error 25 Dim errorMessage As String = _ 26 "Month invalid. Set to month 1." MessageBox.Show(errorMessage, "", _ 29 MessageBoxButtons.OK, MessageBoxIcon.Error) 30 End If mYear = yearValue 33 mDay = CheckDay(dayValue) ' validate day End Sub ' New Declares three integers mMonth, mDay, and mYear Constructor that receives three arguments Assigns values to class variables mMonth, mDay, mYear after error checking

 2002 Prentice Hall. All rights reserved. Outline 32 CDay.vb ' confirm proper day value based on month and year 38 Private Function CheckDay(ByVal testDayValue As Integer) _ 39 As Integer Dim daysPerMonth() As Integer = _ 42 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} If (testDayValue > 0 AndAlso _ 45 testDayValue <= daysPerMonth(mMonth)) Then Return testDayValue 48 End If ' 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 Return testDayValue 56 Else ' inform user of error 59 Dim errorMessage As String = _ 60 "day " & testDayValue & "invalid. Set to day 1. " MessageBox.Show(errorMessage, "", _ 63 MessageBoxButtons.OK, MessageBoxIcon.Error) Return 1 ' leave object in consistent state 66 End If End Function ' CheckDay 69

 2002 Prentice Hall. All rights reserved. Outline 33 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 End Class ' CDay

 2002 Prentice Hall. All rights reserved. Outline 34 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 ' 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) mFirstName = firstNameValue 23 mLastName = lastNameValue ' create CDay instance for employee birthday 26 mBirthDate = New CDay(birthMonthValue, birthDayValue, _ 27 birthYearValue) ' create CDay instance for employee hire date 30 mHireDate = New CDay(hireMonthValue, hireDayValue, _ 31 hireYearValue) 32 End Sub ' New 33 Declares two Private strings and two Private object references Class CEmployee is composed of two references of class CDay, mBirthDate and mHireDate Arguments birthMonthValue, birthDayValue, and birthYearValue were passed to create mBirthDate object Arguments hireMonthValue, hireDayValue, and hireYearValue were passed to create mHireDate object

 2002 Prentice Hall. All rights reserved. Outline 35 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 End Class ' CEmployee

 2002 Prentice Hall. All rights reserved. Outline 36 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) MessageBox.Show(employee.ToStandardString(), _ 13 "Testing Class Employee") 14 End Sub ' Main End Module ' modCompositionTest Instantiate a CEmployee object Outputs in MessageBox.Show

 2002 Prentice Hall. All rights reserved 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

 2002 Prentice Hall. All rights reserved. Outline 38 CTime4.vb 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) Me.mHour = mHour 12 Me.mMinute = mMinute 13 Me.mSecond = mSecond 14 End Sub ' New ' 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 ' 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 End Class ' CTime4 The constructor receives three integer arguments to initialize a CTime4 object Reference Me can refer to any instance variable explicitly Uses reference Me explicitly Uses reference Me implicitly

 2002 Prentice Hall. All rights reserved. Outline 39 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) MessageBox.Show(time.BuildString(), _ 12 "Demonstrating the 'Me' Reference") 13 End Sub ' Main End Module ' modMeTest Invokes method BuildString

 2002 Prentice Hall. All rights reserved Garbage Collection Garbage collector –Resource leaks Objects must have an disciplined, efficient way to return memory and release resources when the program no longer uses those objects –Memory leaks: failure to return memory occupied –In Visual Basic memory is reclaimed automatically by locating objects with no references, hence it experiences rare memory leaks as compared to C and C++ –Some resources, like network connections, are better handled explicitly to be efficient Finalizer method performs termination housekeeping on that object just before the garbage collector reclaims the object's memory. Finalize method is defined in Object

 2002 Prentice Hall. All rights reserved 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 method has no Me reference

 2002 Prentice Hall. All rights reserved. Outline 42 CEmployee2.vb 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 ' CEmployee2 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) mFirstName = firstNameValue 18 mLastName = lastNameValue mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New ' 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 Initializes mCount to 0 by default CEmployee2 constructor increments mCount Finalize method decrements mCount

 2002 Prentice Hall. All rights reserved. Outline 43 CEmployee2.vb 34 ' return first name 35 Public ReadOnly Property FirstName() As String Get 38 Return mFirstName 39 End Get End Property ' FirstName ' return last name 44 Public ReadOnly Property LastName() As String Get 47 Return mLastName 48 End Get End Property ' LastName ' property Count 53 Public ReadOnly Shared Property Count() As Integer Get 56 Return mCount 57 End Get End Property ' Count End Class ' CEmployee2 Member mCount can be referenced without declaring a CEmployee2 object

 2002 Prentice Hall. All rights reserved. Outline 44 SharedTest.vb 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 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee2.Count) Dim employee1 As CEmployee2 = _ 15 New CEmployee2("Susan", "Baker") Dim employee2 As CEmployee2 = _ 18 New CEmployee2("Bob", "Jones") ' output of employee2 after instantiation 21 Console.WriteLine(vbCrLf & _ 22 "Employees after instantiation: " & vbCrLf & _ 23 "via Employee.Count: " & CEmployee2.Count) ' 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) ' mark employee1 and employee2 for garbage collection 32 employee1 = Nothing 33 employee2 = Nothing 34 Declares two CEmployee2 objects and increments mCount by two Sets objects’ references to Nothing

 2002 Prentice Hall. All rights reserved. Outline 45 SharedTest.vb 35 System.GC.Collect() ' request garbage collection 36 End Sub ' Main End Module ' modShared 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

 2002 Prentice Hall. All rights reserved 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 Cannot be modified once initialized

 2002 Prentice Hall. All rights reserved. Outline 47 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 = ' radius is uninitialized constant 10 Public ReadOnly RADIUS As Integer ' constructor of class CCircleConstants 13 Public Sub New(ByVal radiusValue As Integer) 14 RADIUS = radiusValue 15 End Sub ' New End Class ' CCircleConstants Declares PI as a constant variable Declares RADIUS as a ReadOnly variable

 2002 Prentice Hall. All rights reserved. Outline 48 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)) Dim radius As String = Convert.ToString(circle.RADIUS) Dim output As String = "Radius = " & radius & vbCrLf _ 16 & "Circumference = " + String.Format("{0:N3}", _ 17 circle.RADIUS * 2 * CCircleConstants.PI) MessageBox.Show(output, "Circumference", _ 20 MessageBoxButtons.OK, MessageBoxIcon.Information) 21 End Sub ' Main End Module ' modConstAndReadOnly Generates a random number between 1-20 Access constant variable PI Access the ReadOnly variable RADIUS

 2002 Prentice Hall. All rights reserved Data Abstraction and Information Hiding Stacks –Last-in, first out (LIFO) Cafeteria trays that are put on top of each other Stacks offer functions such as push and pop Queue –First-In, first-out (FIFO) Printing machine that prints documents in FIFO order Queue offer functions such as enqueue and dequeue

 2002 Prentice Hall. All rights reserved Software Reusability Rapid application development (RAD) –Software reusability Software reusability speeds the development of powerful, high quality software.

 2002 Prentice Hall. All rights reserved Namespaces and Assemblies 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

 2002 Prentice Hall. All rights reserved. Outline 52 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 ' CEmployee3 constructor 14 Public Sub New(ByVal firstNameValue As String, _ 15 ByVal lastNameValue As String) mFirstName = firstNameValue 18 mLastName = lastNameValue mCount += 1 ' increment shared count of employees 21 Console.WriteLine _ 22 ("Employee object constructor: " & mFirstName & _ 23 " " & mLastName) 24 End Sub ' New ' 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 Declared as Public class CEmployee3

 2002 Prentice Hall. All rights reserved. Outline 53 CEmployee3.vb 34 ' return first name 35 Public ReadOnly Property FirstName() As String Get 38 Return mFirstName 39 End Get End Property ' FirstName ' return last name 44 Public ReadOnly Property LastName() As String Get 47 Return mLastName 48 End Get End Property ' LastName ' property Count 53 Public ReadOnly Shared Property Count() As Integer Get 56 Return mCount 57 End Get End Property ' Count End Class ' CEmployee3

 2002 Prentice Hall. All rights reserved Namespaces and Assemblies Fig. 8.18Simple Class Library.

 2002 Prentice Hall. All rights reserved. Outline 55 AssemblyTest.vb 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 Console.WriteLine("Employees before instantiation: " & _ 12 CEmployee3.Count) Dim employee1 As CEmployee3 = _ 15 New CEmployee3("Susan", "Baker") Dim employee2 As CEmployee3 = _ 18 New CEmployee3("Bob", "Jones") ' output of employee after instantiation 21 Console.WriteLine(vbCrLf & "Employees after instantiation:" _ 22 & vbCrLf & "via Employee.Count: " & CEmployee3.Count) ' 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) ' mark employee1 and employee2 for garbage collection 31 employee1 = Nothing 32 employee2 = Nothing 33 The module imports class CEmployee3

 2002 Prentice Hall. All rights reserved. Outline 56 AssemblyTest.vb 34 System.GC.Collect() ' request garbage collection 35 End Sub ' Main End Module ' modAssemblyTest 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

 2002 Prentice Hall. All rights reserved Class View and Object Browser Class View –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

 2002 Prentice Hall. All rights reserved Class View and Object Browser Fig. 8.20Class View of Fig. 8.1 and Fig. 8.2.

 2002 Prentice Hall. All rights reserved Class View and Object Browser Fig. 8.21Object Browser when user selects Object from CTime.vb,

 2002 Prentice Hall. All rights reserved Class View and Object Browser Fig. 8.21Object Browser when user selects Object from CTime.vb,