slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Microwave Oven Application Building Your Own Classes and Objects PowerPoint Presentation
Download Presentation
Microwave Oven Application Building Your Own Classes and Objects

Loading in 2 Seconds...

play fullscreen
1 / 81

Microwave Oven Application Building Your Own Classes and Objects - PowerPoint PPT Presentation


  • 160 Views
  • Uploaded on

19. Microwave Oven Application Building Your Own Classes and Objects. 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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

Microwave Oven Application Building Your Own Classes and Objects


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide1
19
  • MicrowaveOven Application
  • Building Your OwnClasses and Objects
outline
Outline
  • 19.1 Test-Driving the MicrowaveOven Application
  • 19.2 Designing the MicrowaveOven Application
  • 19.3 Adding a New Class to the Project
  • 19.4 Initializing Class Objects: Constructors
  • 19.5 Properties
outline1
Outline
  • 19.6 Completing the MicrowaveOven Application
  • 19.7 Controlling Access to Members
  • 19.8 Using the Debugger: The Locals Window
objectives
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
introduction
Introduction
  • You have used several .NET classes:
    • Each GUI control is defined as a class.
    • Classes String and Random have been used tocreate 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 ofobject-oriented programming.
    • As with procedures, classes can be reused.
19 1 test driving the microwave oven application
19.1 Test-Driving the MicrowaveOven 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.
test driving the microwave oven application
Test-Driving the MicrowaveOven Application
  • Run the completed application (Fig. 19.1).
    • The Buttons’ FlatStyle property has been set to Flat.
    • The Label’s BorderStyle property has been set to FixedSingle.

Label

Microwave’s glass window

Numerickeypad(Buttonsappear flat)

Figure 19.1|MicrowaveOvenapplication’s Form.

test driving the microwave oven application cont
Test-Driving the MicrowaveOven Application (Cont.)
  • Click the numeric Buttons to enter a time.
  • Note that you can enter no more than four digits—any extra digits will not appear (Fig. 19.2).

Figure 19.2|MicrowaveOven application accepts only four digits.

test driving the microwave oven application cont1
Test-Driving the MicrowaveOven Application (Cont.)
  • Click the ClearButton to clear your input.
  • Enter an invalid input, such as: 7, 2, 3 and 5(Fig. 19.3).

Figure 19.3|MicrowaveOven application with invalid input.

test driving the microwave oven application cont2
Test-Driving the MicrowaveOven Application (Cont.)
  • Click the StartButton, and note that the number of minutes has been reset to 00 (Fig. 19.4).

Color yellow simulates microwave light

Figure 19.4|MicrowaveOven application after invalid input has beenentered and the StartButton clicked.

test driving the microwave oven application cont3
Test-Driving the MicrowaveOven Application (Cont.)
  • Click Clear, enter a cook time of 5 seconds, then click Start (Fig. 19.5).

Figure 19.5|MicrowaveOven application with valid time entered andinside light turned on (it’s now cooking).

test driving the microwave oven application cont4
Test-Driving the MicrowaveOven 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

Figure 19.6|MicrowaveOven application after the cooking time has elapsed.

19 2 designing the microwave oven application
19.2 Designing the MicrowaveOven Application
  • 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 cont
19.2 Designing the MicrowaveOven Application (Cont.)
  • The following pseudocode describes the basic operation of your MicrowaveOven 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 cont1
19.2 Designing the MicrowaveOven Application (Cont.)

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

action control event ace table for the microwave oven application
Action/Control/Event (ACE) Table forthe MicrowaveOven Application
  • Use an ACE table to convert the pseudocode into Visual Basic (Fig. 19.7).

Figure 19.7|ACE table for the MicrowaveOven application. (Part 1 of 2.)

slide17

Action/Control/Event (ACE) Table forthe MicrowaveOven Application (Cont.)

Figure 19.7|ACE table for the MicrowaveOven application. (Part 2 of 2.)

adding a panel control to the microwave oven application
Adding a Panel Control to theMicrowaveOven Application
  • 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 cont
Adding a Panel Control to theMicrowaveOven Application (Cont.)
  • Use instance variable timeIs (Fig. 19.8) to store user input.

Figure 19.8|Variable timeIs contains the user’s input.

gui design tip
GUI Design Tip
  • Use Panels 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 GroupBoxes can contain captions.
gui design tip1
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 Panels to improve user interface readability and organization.
gui design tip2
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 Panels. 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 Panels.
adding a panel control to the microwave oven application cont1
Adding a Panel Control to theMicrowaveOven Application (Cont.)
  • 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 cont2
Adding a Panel Control to theMicrowaveOven Application (Cont.)
  • The template application has several empty event handlers (Fig. 19.10).

startButton_Clickcreates an object to storethe time and begin cooking

clearButton_Click resets variables and Label

DisplayTime formats time information for display

clockTimer_Tickperforms countdownand updates display

Figure 19.10|MicrowaveOven application’s remaining event handlers.

adding a class to the microwave oven application
Adding a Class to the MicrowaveOven Application
  • Select Project>Add Class.
    • Enter the class name (Time) in the Name: field and click Add (Fig. 19.11).

Select Class as new item

Name of new class

Figure 19.11|AddNewItem dialog allows you to create a new class.

adding a class to the microwave oven application cont
Adding a Class to the MicrowaveOven Application (Cont.)
  • The class appears in the SolutionExplorer (Fig. 19.12).

New file displayed in SolutionExplorer

Figure 19.12|SolutionExplorer displaying the new class file.

adding a class to the microwave oven application cont1
Adding a Class to the MicrowaveOven Application (Cont.)
  • Open Time.vb. (Fig. 19.13).
    • Keyword Class indicates that what follows is a class definition.
    • The keywords EndClass 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 cont2
Adding a Class to the MicrowaveOven Application (Cont.)
  • 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 variablesstore minute and second information

Figure 19.14|Time’s instance variables.

good programming practice
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.
defining a constructor
Defining a 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

Figure 19.15|Empty constructor.

common programming error
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.
defining a constructor1
Defining a Constructor
  • 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

Figure 19.16|Constructor initializing instance variables.

error prevention tip
Error-Prevention Tip
  • Providing a constructor to ensure that every object is initialized with meaningful values can help eliminate logic errors.
defining a constructor cont
Defining a Constructor (Cont.)
  • 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 cont1
Defining a Constructor (Cont.)
  • 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.

19 5 properties
19.5 Properties
  • 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 cont
19.5 Properties (Cont.)
  • A propertydefinition may consist of two accessors:
    • The Setaccessor allows clients to set a property.

timeObject.Minute = 35

    • The Getaccessor 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.
defining properties
Defining Properties
  • 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.

Get accessor retrieves data

Set accessor stores data

Figure 19.19|Empty Minute property.

good programming practice1
Good Programming Practice
  • Name each property with a capital first letter.
defining properties cont
Defining Properties (Cont.)
  • When property Minute is referenced, the Get accessor (Fig. 19.20) should return the value of minuteValue.

Returning data from a property

Figure 19.20|Get accessor definition.

defining properties cont1
Defining Properties (Cont.)
  • When property Minute is assigned a value (Fig. 19.21), you want to test whether the value to be assigned is valid.

Validate minute data

Figure 19.21|Set accessor definition.

defining properties cont2
Defining Properties (Cont.)
  • Add the Second property (Fig. 19.22).

Empty property

Figure 19.22|Second property.

defining properties cont3
Defining Properties (Cont.)
  • Second (Fig. 19.23) is similar to Minute, except that variable secondValue is being modified and read.

Second property performs similar data manipulations to Minute property

Figure 19.23|Second property definition.

defining properties cont4
Defining Properties (Cont.)
  • 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).

Safer to assign data to properties rather than instance variables,because Set accessors perform validity checking

Figure 19.24|Constructor using properties to initialize variables.

completing the microwave oven application
Completing the MicrowaveOven Application
  • 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.

Ensure timeIs has four characters forconversion purposes

Figure 19.25|Declaring variables for second and minute values.

completing the microwave oven application cont
Completing the MicrowaveOven Application (Cont.)
  • 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 2starts with the third character, because the first character’s index is 0.

Convert input to seconds and minutes

Figure 19.26|Form minute and second values from input.

completing the microwave oven application cont1
Completing the Microwave Oven Application (Cont.)
  • 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.

Use keyword New to create a new object

Figure 19.27|Creating a Time object.

completing the microwave oven application cont2
Completing the MicrowaveOven Application (Cont.)
  • 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 cont3
Completing the MicrowaveOven Application (Cont.)
  • Note that Time’s properties appear in the IntelliSense window (Fig. 19.29) when you try to access the object’s members.

Time’s propertiesappear in IntelliSense

Figure 19.29|Properties of a programmer-defined type also appear in IntelliSense.

completing the microwave oven application cont4
Completing the MicrowaveOven 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 cont5
Completing the MicrowaveOven Application (Cont.)
  • The Panel’sbackground 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 MicrowaveOven application

Figure 19.31|Clearing the MicrowaveOven input.

completing the microwave oven application cont6
Completing the MicrowaveOven 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 application1
Completing the MicrowaveOven Application
  • 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.

Figure 19.33| Display current input.

completing the microwave oven application cont7
Completing the MicrowaveOven Application (Cont.)
  • Event handler clockTimer_Tick executes every second for as long as the Timer is enabled (Fig.19.34).

Modify time appropriatelyduring countdown

Figure 19.34| Modifying the display during countdown.

19 7 controlling access to members
19.7 Controlling Access to Members
  • Keywords Public and Private are called access modifiers.
    • Class members that are declared Public are availableto any client of the class.
    • Private makes members available only to methodsand properties of the same class.
common programming error1
Common Programming Error
  • Attempting to access a Private class member from outside its class is a compilation error.
software design tip
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.
controlling access to members
Controlling Access to Members
  • In Time.vb, replace keyword Dim in lines 7–8 with keyword Private (Fig.19.35).
  • These instance variables are now accessible onlyto members of class Time.

Figure 19.35|Time’s instance variables are Private.

controlling access to members cont
Controlling Access to Members (Cont.)
  • In MicrowaveOven.vb, replace keyword Dim in lines 4 and 7 with keyword Private (Fig.19.36).

Figure 19.36|MicrowaveOven’s instance variables are Private.

good programming practice2
Good Programming Practice
  • Group all Private class members in a class definition, followed by all Public class members to enhance clarity and readabil­ity.
software design tip1
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.
controlling access to members cont1
Controlling Access to Members (Cont.)
  • 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.

Figure 19.37|MicrowaveOven’s methods are Private.

good programming practice3
Good Programming Practice
  • For clarity, every instance variable or property definition should be preceded by a member-access modifier.
slide64

Outline

  • Figures 19.38 and 19.39 present the sourcecode for the Microwave Oven application.

(1 of 11 )

Make a "beep" sound by calling method Beep

slide65

Outline

(2 of 11 )

slide66

Outline

(3 of 11 )

slide67

Outline

(4 of 11 )

slide68

Outline

(5 of 11 )

slide69

Outline

(6 of 11 )

slide70

Outline

(7 of 11 )

Creating a new object of a programmer-defined type

Accessing variables of a programmer-defined type

slide71

Outline

(8 of 11 )

Use property BackColor to change the Panel’s color

slide72

Outline

(9 of 11 )

Method Substring returns asubset of characters in a String

Method PadLeftcalled to ensure thatStringtimeIscontains four characters

slide73

Outline

(10 of 11 )

slide74

Outline

(11 of 11 )

slide75

Outline

Keyword Class used todefine a class

Time.Vb

(1 of 2 )

New is the constructor

Assign data to properties, rather than directly to instance variables

EndSub keywords end the constructor definition

slide76

Outline

Time.Vb

(2 of 2 )

Keyword Property usedto define a property

Get accessor returns data

Set accessor modifies and validates data

EndProperty keywords end property definition

EndClass keywords end class definition

using the debugger using the locals window
Using the Debugger: Using the Locals Window
  • Set breakpoints in lines 168 and 181 of MicrowaveOven.vbby clicking in the marginindicator bar (Fig. 19.40).

Figure 19.40|MicrowaveOven application with breakpoints added.

using the debugger using the locals window cont
Using the Debugger: Using the Locals Window (Cont.)
  • 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.

Figure 19.41| Empty Locals window.

using the debugger using the locals window cont1
Using the Debugger: Using the Locals Window (Cont.)
  • Set the microwave oven’s time to 1:01, and click the StartButton.
  • 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).

Property of timeObject

Instance variable oftimeObject

Figure 19.42|Locals window displaying the state of timeObject.

using the debugger using the locals window cont2
Using the Debugger: Using the Locals Window (Cont.)
  • Click the debug toolbar’s ContinueButton.
  • Note that the value for the amount of seconds appears in red (Fig.19.43) to indicate it has changed.
  • Click the ContinueButton again.

Changed values

Figure 19.43|Locals window displaying changed variables.

using the debugger using the locals window cont3
Using the Debugger: Using the Locals Window (Cont.)
  • 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 andsets the value to 0.

Value changed by user

Figure 19.44| Changing the value of a variable in the Locals window.