t u t o r i a l 2009 pearson education, inc. all rights reserved. 1 19 microwave oven application...

Click here to load reader

Upload: shannon-mcdonald

Post on 17-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

PowerPoint Presentation 2009 Pearson Education, Inc. All rights reserved.
*
*
19.3 Adding a New Class to the Project
19.4 Initializing Class Objects: Constructors
19.5 Properties
*
19.7 Controlling Access to Members
19.8 Using the Debugger: The Locals Window
*
*
Create your own classes.
Control access to object instance variables.
Use keyword Private.
Objectives
*
Each GUI control is defined as a class.
Classes String and Random have been used to
create objects.
When you use an object of a class, your application is known as a client of that class.
Creating your own classes is a key part of
object-oriented programming.
Introduction
*
19.1 Test-Driving the Microwave Oven Application
*
*
The Buttons’ FlatStyle property has been set to Flat.
The Label’s BorderStyle property has been set to FixedSingle.
Test-Driving the Microwave Oven Application
Figure 19.1 | Microwave Oven application’s Form.
Numeric
keypad
(Buttons
*
Test-Driving the Microwave
Oven Application (Cont.)
Click the numeric Buttons to enter a time.
*
*
Test-Driving the Microwave
Oven Application (Cont.)
Click the Clear Button to clear your input.
Enter an invalid input, such as: 7, 2, 3 and 5
(Fig. 19.3).
*
Figure 19.4 | Microwave Oven application after invalid input has been
entered and the Start Button clicked.
Test-Driving the Microwave
Oven Application (Cont.)
Click the Start Button, and note that the number of minutes has been reset to 00 (Fig. 19.4).
Color yellow simulates microwave light
*
*
Figure 19.5 | Microwave Oven application with valid time entered and
inside light turned on (it’s now cooking).
Test-Driving the Microwave
Oven Application (Cont.)
*
*
Figure 19.6 | Microwave Oven application after the cooking time has elapsed.
Test-Driving the Microwave
Oven Application (Cont.)
After the microwave finishes counting down to zero, you should hear a beep and see a change in the GUI (Fig. 19.6).
Label displays Done! when cooking is finished
*
*
The following pseudocode describes the basic operation of class Time:
When the time object is created:
Assign input to variables for number of minutes and number of seconds
When setting the number of minutes:
If the number of minutes is less than 60
Set the number of minutes to specified value
Else
When setting the number of seconds:
If the number of seconds is less than 60
Set the number of seconds to specified value
Else
19.2 Designing the Microwave Oven Application
*
*
The following pseudocode describes the basic operation of your Microwave Oven class:
When the user clicks a numeric Button:
Sound beep
Store the minutes and seconds
Display the formatted time
Begin countdown—Start timer
19.2 Designing the Microwave
*
Decrease time by one second
Display new time
Stop the countdown
When the user clicks the Clear Button:
Display the text “Microwave Oven”
Clear input and time data
Stop the countdown
19.2 Designing the Microwave
*
Use an ACE table to convert the pseudocode into Visual Basic (Fig. 19.7).
Figure 19.7 | ACE table for the Microwave Oven application. (Part 1 of 2.)
Action/Control/Event (ACE) Table for
the Microwave Oven Application
Click
timeObject
*
Figure 19.7 | ACE table for the Microwave Oven application. (Part 2 of 2.)
Action/Control/Event (ACE) Table for
*
timeObject
timeObject
windowPanel
clearButton
Click
displayLabel
timeIs, timeObject
*
Add a Panel control to the Form by double clicking the Panel control ( ) in the Containers tab of the Toolbox.
The main difference between Panels and GroupBoxes is that GroupBoxes can display a caption.
Name the control windowPanel.
Set its Size to 328, 224 and its Location to 14, 16. Set the BorderStyle property to FixedSingle.
Adding a Panel Control to the
Microwave Oven Application
*
Adding a Panel Control to the
Microwave Oven Application (Cont.)
*
*
GUI Design Tip
*
*
GUI Design Tip
*
*
GUI Design Tip
*
*
One of the numeric Buttons’ Click event handlers is shown in Figure 19.9.
Function Beep causes your computer to make a beeping sound.
The current Button’s number is appended to timeIs.
When a number is entered, play a beep, append the number to the timeIs and display the new time
Figure 19.9 | Typical numeric event handler.
Adding a Panel Control to the
Microwave Oven Application (Cont.)
*
The template application has several empty event handlers (Fig. 19.10).
Adding a Panel Control to the
Microwave Oven Application (Cont.)
startButton_Click
DisplayTime formats time information for display
clockTimer_Tick performs countdown
and updates display
*
Select Project > Add Class.
Enter the class name (Time) in the Name: field and click Add (Fig. 19.11).
Select Class as new item
Figure 19.11 | Add New Item dialog allows you to create a new class.
Adding a Class to the Microwave Oven Application
Name of new class
*
New file displayed in Solution Explorer
Adding a Class to the Microwave
Oven Application (Cont.)
*
Keyword Class indicates that what follows is a class definition.
The keywords End Class indicate the end of the class definition.
Any methods or variables defined in the body of a class are considered to be members of that class.
Empty class definition added by the IDE
Figure 19.13 | Empty class definition.
Adding a Class to the Microwave
Oven Application (Cont.)
*
The value for minutes is stored in minuteValue
the value for seconds is stored in secondValue
Instance variables
Figure 19.14 | Time’s instance variables.
Adding a Class to the Microwave
Oven Application (Cont.)
*
Good Programming Practice
*
*
Add the constructor method New (Fig. 19.15).
Whenever an object of that class is instantiated (created), this constructor method is called.
New is the constructor method
Defining a Constructor
*
Common Programming Error
*
*
Figure 19.16 | Constructor initializing instance variables.
Lines 13–14 (Fig. 19.16) initialize Time’s instance variables to the values of the constructor’s parameter variables.
A Time object can now be created with the statement
timeObject = New Time(5, 3)
*
Error-Prevention Tip
*
*
Add lines 6–7 of Fig. 19.17 to Microwave­Oven.vb.
The class name, Time, is used as a type.
Declare timeObject of programmer-defined type Time
Figure 19.17 | Declaring an object of type Time.
Defining a Constructor (Cont.)
*
The language can be “extended” with new data types.
Your Time class can be displayed in the IntelliSense window (Fig. 19.18).
Time appears as a type in the IDE
Figure 19.18 | Time appearing as a type in an IntelliSense window.
Defining a Constructor (Cont.)
*
Clients of a class usually want to manipulate that class’s instance variables.
A class (Person) that stores information about a person.
Clients who create an object of class Person might want to modify age.
Classes provide properties to allow clients to access and modify instance variables safely.
The code in the property typically checks the value to be assigned and rejects invalid data.
Minute and Second are two properties used in the Time class.
19.5 Properties
*
The Set accessor allows clients to set a property.
timeObject.Minute = 35
minuteValue = timeObject.Minute
Each property typically performs validity checking—to ensure that the data assigned to the property is valid.
Keeping an object’s data valid is also known as keeping that data in a consistent state.
19.5 Properties (Cont.)
*
Add lines 17–18 of Figure 19.19 to Time.vb below the constructor, then press Enter.
Note the syntax used in a property definition:
The first line of the property concludes with the keyword As followed by a data type.
Defining Properties
Get accessor retrieves data
Set accessor stores data
*
*
*
Defining Properties (Cont.)
Returning data from a property
*
*
Defining Properties (Cont.)
Validate minute data
*
*
*
*
Defining Properties (Cont.)
Second property performs similar data manipulations to Minute property
*
*
Defining Properties (Cont.)
Safer to assign data to properties rather than instance variables,
because Set accessors perform validity checking
Use the Minute and Second properties to safely initialize instance variables in the class’s constructor.
*
*
second and minute (Fig. 19.25) store the values entered by the user.
PadLeft appends characters to the beginning of a String.
A given character is added to the beginning of the String until it has the proper length.
Completing the Microwave Oven Application
Figure 19.25 | Declaring variables for second and minute values.
Ensure timeIs has four characters for
conversion purposes
*
Convert.ToInt32 converts the last two characters of timeIs to an Integer (Fig. 19.26).
Arguments passed to Substring indicate the start and end of a subset of characters.
Substring with a single argument returns the characters after the given index.
The argument 2 starts with the third character, because the first character’s index is 0.
Completing the Microwave Oven Application (Cont.)
Figure 19.26 | Form minute and second values from input.
Convert input to seconds and minutes
*
*
When the Time object is instantiated, operator New allocates the memory in which the Time object will be stored.
The Time constructor is called with the values of minute and second (Fig. 19.27).
The New operator returns a reference to the newly created object; this reference is assigned to timeObject.
Completing the Microwave Oven Application (Cont.)
Figure 19.27 | Creating a Time object.
Use keyword New to create a new object
*
*
If the time entered was 3 minutes and 20 seconds, the String that will display for the user is "03:20".
The format control string "{0:D2}:{1:D2}" indicates that arguments take the format D2—thus, 8 would be converted to 08 (Fig. 19.28).
Display cooking time
Completing the Microwave Oven Application (Cont.)
*
*
Figure 19.29 | Properties of a programmer-defined type also appear in IntelliSense.
Time’s properties
appear in IntelliSense
Note that Time’s properties appear in the IntelliSense window (Fig. 19.29) when you try to access the object’s members.
Completing the Microwave Oven Application (Cont.)
*
*
The Timer is started by setting its Enabled property to True (Fig. 19.30).
The Panel’s BackColor property is set to yellow to simulate the light inside the microwave oven.
The Color structure contains several predefined colors.
Start timer and turn light on to indicate microwave oven is cooking
Figure 19.30 | Starting the microwave oven countdown.
Completing the Microwave Oven Application (Cont.)
*
*
The Panel’s background is set to the Panel’s original color with the DefaultBackColor property (Fig. 19.31).
When a Panel is added, its background takes on the default background color of the Form.
Resetting Microwave
Oven application
Completing the Microwave Oven Application (Cont.)
*
*
Method DisplayTime (Fig. 19.32) is called each time the user enters another digit.
String property Length returns the number of characters in a String.
Any characters appended past the first four are removed.
Figure 19.32 | Modifying invalid user input.
Completing the Microwave Oven Application (Cont.)
*
*
Line 152 (Fig. 19.33) appends zeros to the front of timeIs if fewer than four digits were entered.
Lines 155–156 use method Substring to isolate the number of seconds and minutes currently entered.
Completing the Microwave Oven Application
Figure 19.33 | Display current input.
*
*
Event handler clockTimer_Tick executes every second for as long as the Timer is enabled (Fig. 19.34).
Completing the Microwave Oven Application (Cont.)
Figure 19.34 | Modifying the display during countdown.
Modify time appropriately
*
to any client of the class.
Private makes members available only to methods
and properties of the same class.
19.7 Controlling Access to Members
*
*
Common Programming Error
*
*
Software Design Tip
*
*
In Time.vb, replace keyword Dim in lines 7–8 with keyword Private (Fig. 19.35).
These instance variables are now accessible only
to members of class Time.
Controlling Access to Members
*
*
In MicrowaveOven.vb, replace keyword Dim in lines 4 and 7 with keyword Private (Fig. 19.36).
Controlling Access to Members (Cont.)
Figure 19.36 | Microwave Oven’s instance variables are Private.
*
*
Good Programming Practice
*
*
Software Design Tip
*
*
Add keyword Private to the beginning of method DisplayTime (Fig. 19.37).
Event handlers have the keyword Private automatically added to their headers because event handlers are specific to the Form’s class.
Controlling Access to Members (Cont.)
Figure 19.37 | Microwave Oven’s methods are Private.
*
*
Good Programming Practice
For clarity, every instance variable or property definition should be preceded by a member-access
modifier.
*
code for the Microwave Oven application.
Outline
*
4 Private timeIs As String = ""
5
8
10 Private Sub oneButton_Click(ByVal sender As System.Object, _
11 ByVal e As System.EventArgs) Handles oneButton.Click
12
15 DisplayTime() ' display time input properly
16 End Sub ' oneButton_Click
*
19 Private Sub twoButton_Click(ByVal sender As System.Object, _
20 ByVal e As System.EventArgs) Handles twoButton.Click
21
24 DisplayTime() ' display time input properly
25 End Sub ' twoButton_Click
28 Private Sub threeButton_Click(ByVal sender As System.Object, _
29 ByVal e As System.EventArgs) Handles threeButton.Click
30
33 DisplayTime() ' display time input properly
34 End Sub ' threeButton_Click
*
37 Private Sub fourButton_Click(ByVal sender As System.Object, _
38 ByVal e As System.EventArgs) Handles fourButton.Click
39
42 DisplayTime() ' display time input properly
43 End Sub ' fourButton_Click
46 Private Sub fiveButton_Click(ByVal sender As System.Object, _
47 ByVal e As System.EventArgs) Handles fiveButton.Click
48
51 DisplayTime() ' display time input properly
52 End Sub ' fiveButton_Click
*
55 Private Sub sixButton_Click(ByVal sender As System.Object, _
56 ByVal e As System.EventArgs) Handles sixButton.Click
57
60 DisplayTime() ' display time input properly
61 End Sub ' sixButton_Click
64 Private Sub sevenButton_Click(ByVal sender As System.Object, _
65 ByVal e As System.EventArgs) Handles sevenButton.Click
66
69 DisplayTime() ' display time input properly
70 End Sub ' sevenButton_Click
*
73 Private Sub eightButton_Click(ByVal sender As System.Object, _
74 ByVal e As System.EventArgs) Handles eightButton.Click
75
78 DisplayTime() ' display time input properly
79 End Sub ' eightButton_Click
82 Private Sub nineButton_Click(ByVal sender As System.Object, _
83 ByVal e As System.EventArgs) Handles nineButton.Click
84
87 DisplayTime() ' display time input properly
88 End Sub ' nineButton_Click
*
91 Private Sub zeroButton_Click(ByVal sender As System.Object, _
92 ByVal e As System.EventArgs) Handles zeroButton.Click
93
96 DisplayTime() ' display time input properly
97 End Sub ' zeroButton_Click
100 Private Sub startButton_Click(ByVal sender As System.Object, _
101 ByVal e As System.EventArgs) Handles startButton.Click
102
*
Accessing variables of a programmer-defined type
*
105
107 timeIs = timeIs.PadLeft(4, "0"c)
110 second = Convert.ToInt32(timeIs.Substring(2))
113 ' create Time object to contain time entered by user
114 timeObject = New Time(minute, second)
115
117 timeObject.Minute, timeObject.Second)
120
122
*
*
124
128 Private Sub clearButton_Click(ByVal sender As System.Object, _
129 ByVal e As System.EventArgs) Handles clearButton.Click
130
131 ' reset each property or variable to its initial setting
132 displayLabel.Text = "Microwave Oven"
2009 Pearson Education, Inc. All rights reserved.
*
subset of characters in a String
*
144
146
148 If timeIs.Length > 4 Then
149 timeIs = timeIs.Substring(0, 4)
155 second = Convert.ToInt32(display.Substring(2))
2009 Pearson Education, Inc. All rights reserved.
*
160 minute, second)
164 Private Sub clockTimer_Tick(ByVal sender As System.Object, _
165 ByVal e As System.EventArgs) Handles clockTimer.Tick
166
168 If timeObject.Second > 0 Then
169 timeObject.Second -= 1
171 timeObject.Minute, timeObject.Second)
*
173 timeObject.Minute -= 1
174 timeObject.Second = 59
176 timeObject.Minute, timeObject.Second)
179 Beep()
181 windowPanel.BackColor = Control.DefaultBackColor
182 End If
*
Assign data to properties, rather than directly to instance variables
End Sub keywords end the constructor definition
*
3
7 Private minuteValue As Integer
8 Private secondValue As Integer
9
10 ' Time constructor, minute and second supplied
11 Public Sub New(ByVal mm As Integer, ByVal ss As Integer)
12
15 End Sub ' New
19 ' return Minute value
23
*
*
26 ' if minute value entered is valid
27 If (value < 60) Then
28 minuteValue = value
31 End If
33 End Property ' Minute
37 ' return Second value
41
44 ' if second value entered is valid
45 If (value < 60) Then
46 secondValue = value
49 End If
51 End Property ' Second
52 End Class ' Time
*
Set breakpoints in lines 168 and 181 of MicrowaveOven.vb by clicking in the margin
indicator bar (Fig. 19.40).
Using the Debugger:
*
Start the debugger.
Open the Locals window (Fig. 19.41) by selecting Debug > Windows > Locals.
The Locals window allows you to view the state of the variables in the current scope.
Using the Debugger:
*
*
Set the microwave oven’s time to 1:01, and click the Start Button.
The Locals window lists all the variables that are in the scope of clockTimer’s Tick event handler.
To view the contents of timeObject, click the plus box next to the word Me.
Click the plus box next to timeObject (Fig. 19.42).
Using the Debugger:
Figure 19.42 | Locals window displaying the state of timeObject.
Property of timeObject
*
Click the debug toolbar’s Continue Button.
Note that the value for the amount of seconds appears in red (Fig. 19.43) to indicate it has changed.
Click the Continue Button again.
Using the Debugger:
Figure 19.43 | Locals window displaying changed variables.
Changed values
*
In the Locals window, double click the value for property Second and set it to 0 (Fig. 19.44).
Now set the value of the Second property to 100.
The Second property will validates the data and
sets the value to 0.
Using the Debugger:
Using the Locals Window (Cont.)
Figure 19.44 | Changing the value of a variable in the Locals window.
Value changed by user
timeObject
timeObject
timeObject
windowPanel
displayLabel
timeIs,
timeObject
4 Private timeIs As String = ""
5
8
10 Private Sub oneButton_Click(ByVal sender As System.Object, _
11 ByVal e As System.EventArgs) Handles oneButton.Click
12
15 DisplayTime() ' display time input properly
16 End Sub ' oneButton_Click
19 Private Sub twoButton_Click(ByVal sender As System.Object, _
20 ByVal e As System.EventArgs) Handles twoButton.Click
21
24 DisplayTime() ' display time input properly
25 End Sub ' twoButton_Click
29 ByVal e As System.EventArgs) Handles threeButton.Click
30
33 DisplayTime() ' display time input properly
34 End Sub ' threeButton_Click
37 Private Sub fourButton_Click(ByVal sender As System.Object, _
38 ByVal e As System.EventArgs) Handles fourButton.Click
39
42 DisplayTime() ' display time input properly
43 End Sub ' fourButton_Click
46 Private Sub fiveButton_Click(ByVal sender As System.Object, _
47 ByVal e As System.EventArgs) Handles fiveButton.Click
48
51 DisplayTime() ' display time input properly
52 End Sub ' fiveButton_Click
55 Private Sub sixButton_Click(ByVal sender As System.Object, _
56 ByVal e As System.EventArgs) Handles sixButton.Click
57
60 DisplayTime() ' display time input properly
61 End Sub ' sixButton_Click
65 ByVal e As System.EventArgs) Handles sevenButton.Click
66
69 DisplayTime() ' display time input properly
70 End Sub ' sevenButton_Click
74 ByVal e As System.EventArgs) Handles eightButton.Click
75
78 DisplayTime() ' display time input properly
79 End Sub ' eightButton_Click
82 Private Sub nineButton_Click(ByVal sender As System.Object, _
83 ByVal e As System.EventArgs) Handles nineButton.Click
84
87 DisplayTime() ' display time input properly
88 End Sub ' nineButton_Click
91 Private Sub zeroButton_Click(ByVal sender As System.Object, _
92 ByVal e As System.EventArgs) Handles zeroButton.Click
93
96 DisplayTime() ' display time input properly
97 End Sub ' zeroButton_Click
100 Private Sub startButton_Click( ByVal sender As System.Object, _
101 ByVal e As System.EventArgs) Handles startButton.Click
102
105
107 timeIs = timeIs.PadLeft( 4, "0"c)
108
110 second = Convert.ToInt32(t imeIs.Substring(2))
112
113 ' create Time object to contain time entered by user
114 timeObject = New Time(minute, second)
115
117 timeObject.Minute, timeObject.Second)
120
122
124
128 Private Sub clearButton_Click( ByVal sender As System.Object, _
129 ByVal e As System.EventArgs) Handles clearButton.Click
130
131 ' reset each property or variable to its initial setting
132 displayLabel.Text = "Microwave Oven"
140 Private Sub DisplayTime()
144
146
148 If timeIs.Length > 4 Then
149 timeIs = timeIs.Substring( 0, 4)
150 End If
153
155 second = Convert.ToInt32(d isplay.Substring(2))
157
159 displayLabel.Text = String.Format("{0:D2}:{1:D2}", _
160 minute, second)
164 Private Sub clockTimer_Tick(ByVal sender As System.Object, _
165 ByVal e As System.EventArgs) Handles clockTimer.Tick
166
168 If timeObject.Second > 0 Then
169 timeObject.Second -= 1
171 timeObject.Minute, timeObject.Second)
173 timeObject.Minute -= 1
174 timeObject.Second = 59
176 timeObject.Minute, timeObject.Second)
179 Beep()
181 windowPanel.BackColor = Control.DefaultBackColor
182 End If
3
7 Private minuteValue As Integer
8 Private secondValue As Integer
9
10 ' Time constructor, mi nute and second supplied
11 Public Sub New(ByVal mm As Integer, ByVal ss As Integer)
12
15 End Sub ' New
19 ' return Minute value
23
26 ' if minute value entered is valid
27 If (value < 60) Then
28 minuteValue = value
31 End If
33 End Property ' Minute
37 ' return Second value
41
44 ' if second value entered is valid
45 If (value < 60) Then
46 secondValue = value
49 End If
51 End Property ' Second
52 End Class ' Time