Presentation is loading. Please wait.

Presentation is loading. Please wait.

T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 19 Microwave Oven Application Building Your Own Classes and Objects.

Similar presentations


Presentation on theme: "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 19 Microwave Oven Application Building Your Own Classes and Objects."— Presentation transcript:

1 T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 19 Microwave Oven Application Building Your Own Classes and Objects

2  2009 Pearson Education, Inc. All rights reserved. 2 Outline 19.1 Test-Driving the Microwave Oven Application 19.2 Designing the Microwave Oven Application 19.3 Adding a New Class to the Project 19.4 Initializing Class Objects: Constructors 19.5 Properties

3  2009 Pearson Education, Inc. All rights reserved. 3 Outline 19.6 Completing the Microwave Oven Application 19.7 Controlling Access to Members 19.8 Using the Debugger: The Locals Window

4  2009 Pearson Education, Inc. All rights reserved. 4 In this tutorial you will learn: ■Create your own classes. ■Create and use objects of your own classes. ■Control access to object instance variables. ■Use keyword Private. ■Create your own properties. ■Use the Panel control. ■Use String methods PadLeft and Substring. Objectives

5  2009 Pearson Education, Inc. All rights reserved. 5 ■You have used several.NET classes: – 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. – As with procedures, classes can be reused. Introduction

6 Application Requirements  2009 Pearson Education, Inc. All rights reserved. 6 19.1 Test-Driving the Microwave Oven Application An electronics company has asked you to develop an application that simulates a microwave oven. The oven contains a keypad that allows the user to specify the microwave cook time. Once a time is entered, the user clicks the Start Button to begin the cooking process. The microwave’s glass window changes color (from gray to yellow), and a timer counts down one second at a time. Once the time expires, the color of the microwave’s glass window returns to gray and the microwave displays the text “Done!” The user can click the Clear Button at any time to stop the microwave and enter a new time. A beep is sounded whenever a Button is clicked and when the microwave oven has finished a countdown.

7  2009 Pearson Education, Inc. All rights reserved. 7 ■Run the completed application (Fig. 19.1). –The Button s’ 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 appear flat) Label Microwave’s glass window

8  2009 Pearson Education, Inc. All rights reserved. 8 Figure 19.2 | Microwave Oven application accepts only four digits. Test-Driving the Microwave Oven Application (Cont.) ■Click the numeric Button s to enter a time. ■Note that you can enter no more than four digits—any extra digits will not appear (Fig. 19.2).

9  2009 Pearson Education, Inc. All rights reserved. 9 Figure 19.3 | Microwave Oven application with invalid input. 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).

10  2009 Pearson Education, Inc. All rights reserved. 10 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

11  2009 Pearson Education, Inc. All rights reserved. 11 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.) ■Click Clear, enter a cook time of 5 seconds, then click Start (Fig. 19.5).

12  2009 Pearson Education, Inc. All rights reserved. 12 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 Color returns to default color to simulate that cooking has finished

13  2009 Pearson Education, Inc. All rights reserved. 13 ■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 Set the number of minutes to 0 When setting the number of seconds: If the number of seconds is less than 60 Set the number of seconds to specified value Else Set the number of seconds to 0 19.2 Designing the Microwave Oven Application

14  2009 Pearson Education, Inc. All rights reserved. 14 ■The following pseudocode describes the basic operation of your Microwave Oven class: When the user clicks a numeric Button: Sound beep Display the formatted time When the user clicks the Start Button: Store the minutes and seconds Display the formatted time Begin countdown—Start timer Turn the microwave light on 19.2 Designing the Microwave Oven Application (Cont.)

15  2009 Pearson Education, Inc. All rights reserved. 15 When the timer ticks (once per second): Decrease time by one second Display new time If new time is zero Stop the countdown Sound beep Display text “Done!” Turn the microwave light off When the user clicks the Clear Button: Display the text “Microwave Oven” Clear input and time data Stop the countdown Turn the microwave light off 19.2 Designing the Microwave Oven Application (Cont.)

16  2009 Pearson Education, Inc. All rights reserved. 16 ■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

17  2009 Pearson Education, Inc. All rights reserved. 17 Figure 19.7 | ACE table for the Microwave Oven application. (Part 2 of 2.) Action/Control/Event (ACE) Table for the Microwave Oven Application (Cont.)

18  2009 Pearson Education, Inc. All rights reserved. 18 ■Add a Panel control to the Form by double clicking the Panel control ( ) in the Containers tab of the Toolbox. –The main difference between Panel s and GroupBox es is that GroupBox es 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

19  2009 Pearson Education, Inc. All rights reserved. 19 Figure 19.8 | Variable timeIs contains the user’s input. Adding a Panel Control to the Microwave Oven Application (Cont.) ■Use instance variable timeIs (Fig. 19.8) to store user input.

20  2009 Pearson Education, Inc. All rights reserved. 20 GUI Design Tip Use Panel s to organize groups of related controls where the purpose of the controls is obvious. If the purpose of the controls is not obvious, use a GroupBox rather than a Panel, because GroupBox es can contain captions.

21  2009 Pearson Education, Inc. All rights reserved. 21 GUI Design Tip Although it is possible to have a Panel without a border (by setting the BorderStyle property to None ), use borders on your Panel s to improve user interface readability and organization.

22  2009 Pearson Education, Inc. All rights reserved. 22 GUI Design Tip A Panel can display scrollbars when it is not large enough to display all of its controls. To increase usability, we suggest avoiding the use of scrollbars on Panel s. If a Panel is not large enough to display all of its contents, increase the size of the Panel or place the content in multiple Panel s.

23  2009 Pearson Education, Inc. All rights reserved. 23 ■One of the numeric Button s’ 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.)

24  2009 Pearson Education, Inc. All rights reserved. 24 ■The template application has several empty event handlers (Fig. 19.10). Adding a Panel Control to the Microwave Oven Application (Cont.) Figure 19.10 | Microwave Oven application’s remaining event handlers. startButton_Click creates an object to store the time and begin cooking clearButton_Click resets variables and Label DisplayTime formats time information for display clockTimer_Tick performs countdown and updates display

25  2009 Pearson Education, Inc. All rights reserved. 25 ■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

26  2009 Pearson Education, Inc. All rights reserved. 26 Figure 19.12 | Solution Explorer displaying the new class file. ■The class appears in the Solution Explorer (Fig. 19.12). New file displayed in Solution Explorer Adding a Class to the Microwave Oven Application (Cont.)

27  2009 Pearson Education, Inc. All rights reserved. 27 ■Open Time.vb. (Fig. 19.13). –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.)

28  2009 Pearson Education, Inc. All rights reserved. 28 ■The Time class (Fig. 19.14) stores a time value: –The value for minutes is stored in minuteValue –the value for seconds is stored in secondValue Instance variables store minute and second information Figure 19.14 | Time ’s instance variables. Adding a Class to the Microwave Oven Application (Cont.)

29  2009 Pearson Education, Inc. All rights reserved. 29 Good Programming Practice Add comments at the beginning of your classes to increase readability. The comments should indicate the name of the file that contains the class and the purpose of the class being defined.

30  2009 Pearson Education, Inc. All rights reserved. 30 Figure 19.15 | Empty constructor. ■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

31  2009 Pearson Education, Inc. All rights reserved. 31 Common Programming Error Attempting to declare a constructor as a Function procedure instead of as a Sub procedure and attempting to Return a value from a constructor are both syntax errors.

32  2009 Pearson Education, Inc. All rights reserved. 32 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) Initialize instance variables Defining a Constructor

33  2009 Pearson Education, Inc. All rights reserved. 33 Error-Prevention Tip Providing a constructor to ensure that every object is initialized with meaningful values can help eliminate logic errors.

34  2009 Pearson Education, Inc. All rights reserved. 34 ■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.)

35  2009 Pearson Education, Inc. All rights reserved. 35 ■Visual Basic is known as an extensible language. –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.)

36  2009 Pearson Education, Inc. All rights reserved. 36 ■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

37  2009 Pearson Education, Inc. All rights reserved. 37 ■A property definition may consist of two accessors: –The Set accessor allows clients to set a property. timeObject.Minute = 35 –The Get accessor allows clients to get a property. 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.)

38  2009 Pearson Education, Inc. All rights reserved. 38 ■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 Figure 19.19 | Empty Minute property. Get accessor retrieves data Set accessor stores data

39  2009 Pearson Education, Inc. All rights reserved. 39 Good Programming Practice Name each property with a capital first letter.

40  2009 Pearson Education, Inc. All rights reserved. 40 Figure 19.20 | Get accessor definition. Defining Properties (Cont.) Returning data from a property ■When property Minute is referenced, the Get accessor (Fig. 19.20) should return the value of minuteValue.

41  2009 Pearson Education, Inc. All rights reserved. 41 Figure 19.21 | Set accessor definition. Defining Properties (Cont.) Validate minute data ■When property Minute is assigned a value (Fig. 19.21), you want to test whether the value to be assigned is valid.

42  2009 Pearson Education, Inc. All rights reserved. 42 Figure 19.22 | Second property. Defining Properties (Cont.) Empty property ■Add the Second property (Fig. 19.22).

43  2009 Pearson Education, Inc. All rights reserved. 43 Figure 19.23 | Second property definition. Defining Properties (Cont.) Second property performs similar data manipulations to Minute property ■ Second (Fig. 19.23) is similar to Minute, except that variable secondValue is being modified and read.

44  2009 Pearson Education, Inc. All rights reserved. 44 Figure 19.24 | Constructor using properties to initialize variables. 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. ■When a client calls New and passes values for mm and ss, the constructor calls the Set accessors to validate the values (Fig. 19.24).

45  2009 Pearson Education, Inc. All rights reserved. 45 ■ 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

46  2009 Pearson Education, Inc. All rights reserved. 46 ■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

47  2009 Pearson Education, Inc. All rights reserved. 47 ■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

48  2009 Pearson Education, Inc. All rights reserved. 48 ■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 Figure 19.28 | Displaying time information with separating colon. Completing the Microwave Oven Application (Cont.)

49  2009 Pearson Education, Inc. All rights reserved. 49 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.)

50  2009 Pearson Education, Inc. All rights reserved. 50 ■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.)

51  2009 Pearson Education, Inc. All rights reserved. 51 ■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 Figure 19.31 | Clearing the Microwave Oven input. Completing the Microwave Oven Application (Cont.)

52  2009 Pearson Education, Inc. All rights reserved. 52 ■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.)

53  2009 Pearson Education, Inc. All rights reserved. 53 ■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.

54  2009 Pearson Education, Inc. All rights reserved. 54 ■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 during countdown

55  2009 Pearson Education, Inc. All rights reserved. 55 ■Keywords Public and Private are called access modifiers. –Class members that are declared Public are available 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

56  2009 Pearson Education, Inc. All rights reserved. 56 Common Programming Error Attempting to access a Private class member from outside its class is a compilation error.

57  2009 Pearson Education, Inc. All rights reserved. 57 Software Design Tip Declare all instance variables of a class as Private. When necessary, provide Public properties to set and get the values of Private instance variables.

58  2009 Pearson Education, Inc. All rights reserved. 58 ■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 Figure 19.35 | Time ’ s instance variables are Private.

59  2009 Pearson Education, Inc. All rights reserved. 59 ■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.

60  2009 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice Group all Private class members in a class definition, followed by all Public class members to enhance clarity and readabil­ity.

61  2009 Pearson Education, Inc. All rights reserved. 61 Software Design Tip It is possible to declare the Get and Set accessors with different access modifiers. One of the accessors must have the same access as the property, and the other must be more restrictive than the property. For example, in a Public property, the Get accessor could be Public and the Set accessor could be Private to create a property that is "read-only" to the class’s clients.

62  2009 Pearson Education, Inc. All rights reserved. 62 ■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.

63  2009 Pearson Education, Inc. All rights reserved. 63 Good Programming Practice For clarity, every instance variable or property definition should be preceded by a member-access modifier.

64  2009 Pearson Education, Inc. All rights reserved. 64 ■Figures 19.38 and 19.39 present the source code for the Microwave Oven application. Outline (1 of 11 ) Make a "beep" sound by calling method Beep

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline (2 of 11 )

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline (3 of 11 )

67  2009 Pearson Education, Inc. All rights reserved. 67 Outline (4 of 11 )

68  2009 Pearson Education, Inc. All rights reserved. 68 Outline (5 of 11 )

69  2009 Pearson Education, Inc. All rights reserved. 69 Outline (6 of 11 )

70  2009 Pearson Education, Inc. All rights reserved. 70 Outline (7 of 11 ) Creating a new object of a programmer-defined type Accessing variables of a programmer-defined type

71  2009 Pearson Education, Inc. All rights reserved. 71 Outline (8 of 11 ) Use property BackColor to change the Panel’s color

72  2009 Pearson Education, Inc. All rights reserved. 72 Outline (9 of 11 ) Method Substring returns a subset of characters in a String Method PadLeft called to ensure that String timeIs contains four characters

73  2009 Pearson Education, Inc. All rights reserved. 73 Outline (10 of 11 )

74  2009 Pearson Education, Inc. All rights reserved. 74 Outline (11 of 11 )

75  2009 Pearson Education, Inc. All rights reserved. 75 Outline Time.Vb (1 of 2 ) Keyword Class used to define a class New is the constructor Assign data to properties, rather than directly to instance variables End Sub keywords end the constructor definition

76  2009 Pearson Education, Inc. All rights reserved. 76 Time.Vb (2 of 2 ) Outline Keyword Property used to define a property Get accessor returns data Set accessor modifies and validates data End Property keywords end property definition End Class keywords end class definition

77  2009 Pearson Education, Inc. All rights reserved. 77 ■Set breakpoints in lines 168 and 181 of MicrowaveOven.vb by clicking in the margin indicator bar (Fig. 19.40). Figure 19.40 | Microwave Oven application with breakpoints added. Using the Debugger: Using the Locals Window

78  2009 Pearson Education, Inc. All rights reserved. 78 ■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: Using the Locals Window (Cont.) Figure 19.41 | Empty Locals window.

79  2009 Pearson Education, Inc. All rights reserved. 79 ■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: Using the Locals Window (Cont.) Figure 19.42 | Locals window displaying the state of timeObject. Property of timeObject Instance variable of timeObject

80  2009 Pearson Education, Inc. All rights reserved. 80 ■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: Using the Locals Window (Cont.) Figure 19.43 | Locals window displaying changed variables. Changed values

81  2009 Pearson Education, Inc. All rights reserved. 81 ■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


Download ppt "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 19 Microwave Oven Application Building Your Own Classes and Objects."

Similar presentations


Ads by Google