introduction to classes and objects - kent state...

53
2009 Pearson Education, Inc. All rights reserved. 1 4 Introduction to Classes and Objects

Upload: others

Post on 17-Jul-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

1

4Introduction to

Classes and Objects

Page 2: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

2

You will see something new. Two things.And I call them Thing One and Thing Two.

– Dr. Theodor Seuss Geisel

Nothing can have value without beingan object of utility.

– Karl Marx

Page 3: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

3

Your public servants serve you right. – Adlai E. Stevenson

Knowing how to answer one who speaks, To reply to one who sends a message.

– Amenemope

Page 4: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

4

OBJECTIVESIn this chapter you will learn: What classes, objects, methods, instance variables

and properties are. How to declare a class and use it to create an

object. How to implement a class’s behaviors as methods. How to implement a class’s attributes as instance

variables and properties. How to call an object’s methods to make

them perform their tasks.

Page 5: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

5

OBJECTIVES The differences between instance variables

of a class and local variables of a method. How to use a constructor to ensure that an

object’s attributes are initialized when the object is created. The differences between value types and

reference types. How to use properties to ensure that only valid

data is placed in attributes.

Page 6: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

6

4.1 Introduction4.2 Classes, Objects, Methods and Instance Variables4.3 Declaring a Class with a Method and Instantiating

an Object of a Class4.4 Declaring a Method with a Parameter4.5 Instance Variables and Properties4.6 Value Types and Reference Types4.7 Initializing Objects with Constructors4.8 Validating Data with Set Accessors in Properties4.9 (Optional) Software Engineering Case Study:

Identifying the Classes in the ATM Requirements Document

Page 7: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

7

4.2 Classes, Objects, Methods and Instance Variables• In Visual Basic, a program unit called a class houses

one or more methods.– Performing a task in a program requires a method.

• Just as a car is built from engineering drawings, you build an object from a class.

• A car receives messages, such as pressure on the brake pedal, telling it to internally perform complex actions.

• Cars have individual attributes such as color, model, and gas left in the tank.

Page 8: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

8

4.3 Declaring a Class with a Method and Instantiating an Object of a Class

• Right click the project name in the SolutionExplorer and select Add > Class…

• Enter the name of your new file (GradeBook.vb).

Page 9: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

9

1 ' Fig. 4.1: GradeBook.vb

2 ' Class declaration with one method.

3 Public Class GradeBook

4 ' display a welcome message to the GradeBook user

5 Public Sub DisplayMessage()

6 Console.WriteLine("Welcome to the Grade Book!")

7 End Sub ' DisplayMessage

8 End Class ' GradeBook

Outline

GradeBook.vb

Displaying a message on the screen

Fig. 4.1 | Class declaration with one method.

Page 10: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

10

4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)

• A method that begins with keyword Public can be called from outside its class.

• Keyword Sub indicates that this method will perform a task but will not return any information to its calling method.

• By convention, method names begin with an uppercase letter and all subsequent words in the name begin with a capital letter.

• The parentheses after the method name are used to indicate any parameters.

Page 11: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

11

4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)

• Typically, you cannot call a method that belongs to another class until you create an object of that class.

• Each new class you create becomes a new type in Visual Basic.

– This is one reason why Visual Basic is known as an extensible language.

Page 12: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

12

1 ' Fig. 4.2: GradeBookTest.vb

2 ' Create a GradeBook object and call its DisplayMessage method.

3 Module GradeBookTest

4 ' Main begins program execution

5 Sub Main()

6 ' initialize gradeBook to refer to a new GradeBook object

7 Dim gradeBook As New GradeBook()

8 9 ' call gradeBook's DisplayMessage method

10 gradeBook.DisplayMessage() 11 End Sub ' Main 12 End Module ' GradeBookTest

Welcome to the Grade Book!

Outline

GradeBookTest.vb

Object creation expression (constructor)

• Variable gradeBook is initialized with the result of the object creation expression New GradeBook()(Fig. 4.2).

Uses object created in line 7

Fig. 4.2 | Creating an object of class GradeBook and callingits DisplayMessage method.

Page 13: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

13

4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)

• Figure 4.3 presents a UML class diagram for class GradeBook.

– The top compartment contains the name of the class.– The middle compartment contains the class’s attributes.– The bottom compartment contains the class’s operations.

• The plus sign (+) in front of the operation name indicates a public operation.

Fig. 4.3 | UML class diagram indicating that class GradeBook has apublic DisplayMessage operation.

Page 14: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

14

1 ' Fig. 4.4: GradeBook.vb

2 ' Class declaration with a method that has a parameter.

3 Public Class GradeBook

4 ' display a welcome message to the GradeBook user

5 Public Sub DisplayMessage(ByVal courseName As String)

6 Console.WriteLine( _

7 "Welcome to the grade book for " & vbNewLine & courseName & "!")

8 End Sub ' DisplayMessage

9 End Class ' GradeBook

Outline

GradeBook.vb

• A method can require parameters to perform its task.• A method call supplies values—called arguments—for

each parameter.

The new DisplayMessagerequires a course name to output

Fig. 4.4 | Class declaration with one method that has a parameter.

Page 15: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

15

1 ' Fig. 4.5: GradeBookTest.vb

2 ' Create a GradeBook object and call its DisplayMessage method.

3 Module GradeBookTest

4 ' Main begins program execution

5 Sub Main()

6 ' initialize gradeBook to reference a new gradeBook object

7 Dim gradeBook As New GradeBook()

8 9 ' prompt for the course name

10 Console.WriteLine("Please enter the course name:") 11 12 ' read the course name 13 Dim nameOfCourse As String = Console.ReadLine() 14 15 Console.WriteLine() ' output a blank line

Outline

GradeBookTest.vb

(1 of 2 )

gradeBook references a new GradeBook object.

Assigning user input to nameOfCourse

Fig. 4.5 | Creating a GradeBook object and passing a String toits DisplayMessage method. (Part 1 of 2.)

Page 16: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

16

16 17 ' call gradeBook's DisplayMessage method 18 ' and pass nameOfCourse as an argument 19 gradeBook.DisplayMessage(nameOfCourse) 20 End Sub ' Main 21 End Module ' GradeBookTest

Please enter the course name:

CS101 Introduction to Visual Basic Programming

Welcome to the grade book for

CS101 Introduction to Visual Basic Programming!

Outline

nameOfCourse is passed to methodDisplayMessage

GradeBookTest.vb

(2 of 2 )

Fig. 4.5 | Creating a GradeBook object and passing a String toits DisplayMessage method. (Part 2 of 2.)

Page 17: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

17

4.4 Declaring a Method with a Parameter (Cont.)

• Each parameter must have a type and an identifier.• Multiple parameters can be listed, separated by

commas.• The number of arguments in a method call must match

the number of parameters.

Page 18: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

18

4.4 Declaring a Method with a Parameter (Cont.)

• The UML class diagram in Fig. 4.6 models class GradeBook.

Fig. 4.6 | UML class diagram indicating that class GradeBook has a DisplayMessageoperation with a courseName parameter of type String.

Page 19: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

19

4.5 Instance Variables and Properties

• Variables declared in the body of a method are known as local variables and can be used only inside that method.

• Attributes are represented as instance variables and are declared inside a class declaration (but outside of other parts of the class).

• Each object of a class maintains its own copy of an instance variable.

Page 20: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

20

1 ' Fig. 4.7: GradeBook.vb

2 ' GradeBook class that contains instance variable courseNameValue

3 ' and a property to get and set its value.

4 Public Class GradeBook

5 Private courseNameValue As String ' course name for this GradeBook

6 7 ' property CourseName

8 Public Property CourseName() As String

9 Get ' retrieve courseNameValue

10 Return courseNameValue 11 End Get 12 13 Set(ByVal value As String) ' set courseNameValue 14 courseNameValue = value ' store the course name in the object 15 End Set 16 End Property ' CourseName

Outline

GradeBook.vb

(1 of 2 )

Instance variable courseNameValue is declared as a String.

Property’s Get accessor

Property’s Set accessor

• Class GradeBook (Fig 4.7) now maintains the course name as an instance variable so that it can be stored and modified.

Fig. 4.7 | GradeBook class that contains a courseNameValue instancevariable and a CourseName property. (Part 1 of 2.)

Page 21: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

21

17 18 ' display a welcome message to the GradeBook user 19 Public Sub DisplayMessage() 20 ' use property CourseName to display the 21 ' name of the course this GradeBook represents 22 Console.WriteLine("Welcome to the grade book for " _ 23 & vbNewLine & CourseName & "!") 24 End Sub ' DisplayMessage 25 End Class ' GradeBook

Outline

GradeBook.vb

(2 of 2 )

Outputs a message that includes the value of CourseName.

Fig. 4.7 | GradeBook class that contains a courseNameValue instancevariable and a CourseName property. (Part 2 of 2.)

Page 22: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

22

4.5 Instance Variables and Properties (Cont.)

• Private variables, methods and properties are accessible only in the class in which they are declared.

• Declaring Private instance variables is known as information hiding.

– Variable courseNameValue is hidden in the object.

Page 23: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

23

4.5 Instance Variables and Properties (Cont.)

Software Engineering Observation 4.1Precede every instance variable declaration, method declaration and property declaration with an access modifier. In most cases, instance variables should be declared Private, and methods and properties should be declared Public. Instance variables are Private by default, and methods and properties are Public by default.

Software Engineering Observation 4.2Declaring the instance variables of a class as Private and the methods of the class as Public facilitates debugging, because problems with data manipulations are localized to the class’s methods and properties.

Page 24: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

24

• The Get accessor begins with the keyword Get and ends with the keywords End Get.

– The accessor’s body contains a Return statement, which consists of the keyword Return followed by an expression.

• Using the value of gradeBook.CourseNameimplicitly executes CourseName’s Get accessor:

Dim theCourseName As String = gradeBook.CourseName

4.5 Instance Variables and Properties (Cont.)

Page 25: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

25

• The Set accessor begins with the keyword Set and ends with the keywords End Set.

• Assigning a value to gradeBook.CourseName implicitly executes CourseName’s Set accessor:gradeBook.CourseName = "CS100 Introduction to Computers"

• The order in which methods and properties are declared in a class does not determine when they are called at execution time.

• Either property accessor can be omitted (making a property read-only or write-only).

4.5 Instance Variables and Properties (Cont.)

Page 26: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

26

1 ' Fig. 4.8: GradeBookTest.vb

2 ' Create and manipulate a GradeBook object.

3 Module GradeBookTest

4 ' Main begins program execution

5 Sub Main()

6 ' line 8 creates a GradeBook object that is referenced by

7 ' variable gradeBook of type GradeBook

8 Dim gradeBook As New GradeBook

9 10 ' display initial value of property CourseName (invokes Get) 11 Console.WriteLine( _ 12 "Initial course name is: " & gradeBook.CourseName & vbNewLine) 13 14 ' prompt for course name 15 Console.WriteLine("Please enter the course name:")

Outline

GradeBookTest.vb

(1 of 2 )

• Module GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName.

• Variables have a default initial value.– String is a reference type; the default value for reference

types is Nothing.

Uses CourseName’s Get accessor.

Fig. 4.8 | Creating and manipulating a GradeBookobject (invoking properties). (Part 1 of 2.)

Page 27: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

27

16 17 ' read course name 18 Dim theName As String = Console.ReadLine() 19 20 gradeBook.CourseName = theName ' set the CourseName (invokes Set) 21 Console.WriteLine() ' output a blank line 22 23 ' display welcome message including the course name (invokes Get) 24 gradeBook.DisplayMessage() 25 End Sub ' Main 26 End Module ' GradeBookTest

Initial course name is:

Please enter the course name:

CS101 Introduction to Visual Basic Programming

Welcome to the grade book for

CS101 Introduction to Visual Basic Programming!

Outline

GradeBookTest.vb

(2 of 2 )

Uses CourseName’s Set accessor.

Fig. 4.8 | Creating and manipulating a GradeBookobject (invoking properties). (Part 2 of 2.)

Page 28: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

28

4.5 Instance Variables and Properties (Cont.) GradeBook’s UML Class Diagram with a Property• The property is listed as a public attribute (Fig. 4.9),

as indicated by the plus (+) sign. • Using the word “Property” in guillemets (« and »)

helps distinguish it from other attributes.• To indicate that an attribute or operation is private,

use a minus sign (–).

Fig. 4.9 | UML class diagram indicating that class GradeBook has a courseNameValueattribute of type String, one property and one method.

Page 29: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

29

4.5 Instance Variables and Properties (Cont.)

Software Engineering Observation 4.3Accessing Private data through Set and Get accessors not only protects the instance variables from receiving invalid values, but also hides the internal representation of the instance variables from that class’s clients. Thus, if representation of the data changes (often, to reduce the amount of required storage or to improve perfor-mance), only the properties’ implementations need to change—the clients’ implementations need not change as long as the services provided by the properties are preserved.

Page 30: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

30

4.6 Value Types and Reference Types

• Data types in Visual Basic are divided into value types and reference types.

– A variable of a value type simply contains a value of that type (Fig. 4.10).

Fig. 4.10 | Value type variable.

Page 31: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

31

4.6 Value Types and Reference Types (Cont.)

• A variable of a reference type contains the memory address where the data referred to by that variable is stored.

• Reference type instance variables are initialized by default to the value Nothing.

• A reference to an object is used to invoke the object’s methods and access the object’s properties.gradeBook.CourseName = theName ' set the CourseName (invokes Set)

Page 32: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

32

4.7 Initializing Objects with Constructors

• A constructor initializes an object of the class.• The New keyword calls the class’s constructor to

perform the initialization (Fig. 4.11).

Dim gradeBook As New GradeBook( _“CS101 Introduction to Visual Basic Programming")

Fig. 4.11 | Reference type variable.

Page 33: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

33

1 ' Fig. 4.12: GradeBook.vb

2 ' GradeBook class with a constructor to initialize the course name.

3 Public Class GradeBook

4 Private courseNameValue As String ' course name for this GradeBook

5 6 ' constructor initializes course name with String supplied as argument

7 Public Sub New(ByVal name As String)

8 CourseName = name ' initialize courseNameValue via property

9 End Sub ' New

10 11 ' property CourseName 12 Public Property CourseName() As String 13 Get ' retrieve courseNameValue 14 Return courseNameValue 15 End Get

Outline

GradeBook.vb

(1 of 2 )

This constructor specifies in its parameter list the data it requires to perform its task.

Fig. 4.12 | GradeBook class with a constructor that receives acourse name. (Part 1 of 2.)

Page 34: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

34

16 17 Set(ByVal value As String) ' set courseNameValue 18 courseNameValue = value ' store the course name in the object 19 End Set 20 End Property ' CourseName 21 22 ' display a welcome message to the GradeBook user 23 Public Sub DisplayMessage() 24 ' use property CourseName to display the 25 ' name of the course this GradeBook represents 26 Console.WriteLine("Welcome to the grade book for " _ 27 & vbNewLine & CourseName & "!") 28 End Sub ' DisplayMessage 29 End Class ' GradeBook

Outline

GradeBook.vb

(2 of 2 )

Fig. 4.12 | GradeBook class with a constructor that receives acourse name. (Part 2 of 2.)

Page 35: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

35

1 ' Fig. 4.13: GradeBookTest.vb

2 ' GradeBook constructor used to specify the course name at the

3 ' time each GradeBook object is created.

4 Module GradeBookTest

5 ' Main begins program execution

6 Sub Main()

7 ' create GradeBook object

8 Dim gradeBook1 As New GradeBook( _

9 "CS101 Introduction to Visual Basic Programming")

10 Dim gradeBook2 As New GradeBook( _ 11 "CS102 Data Structures in Visual Basic") 12

Outline

GradeBookTest.vb

(1 of 2 )

Fig. 4.13 | Constructor used to initialize GradeBook objects. (Part 1 of 2.)

Page 36: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

36

13 ' display initial value of CourseName for each GradeBook 14 Console.WriteLine( _ 15 "gradeBook1 course name is: " & gradeBook1.CourseName) 16 Console.WriteLine( _ 17 "gradeBook2 course name is: " & gradeBook2.CourseName) 18 End Sub ' Main 19 End Module ' GradeBookTest

gradeBook1 course name is: CS101 Introduction to Visual Basic Programming

gradeBook2 course name is: CS102 Data Structures in Visual Basic

Outline

GradeBookTest.vb

(2 of 2 )

Error-Prevention Tip 4.1Unless default initialization of your class’s instance variables is acceptable, provide a constructor to ensure that these variables are properly initialized with meaningful values when each new object of your class is created.

Fig. 4.13 | Constructor used to initialize GradeBook objects. (Part 2 of 2.)

Page 37: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

37

4.7 Initializing Objects with Constructors (Cont.)

Adding the Constructor to Class GradeBook’s UML Class Diagram

• The UML class diagram of Fig. 4.14 models the class GradeBook.

• The word “constructor” is between guillemets (« and » ).

Fig. 4.14 | UML class diagram indicating that class GradeBook has aconstructor that has a name parameter of type String.

Page 38: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

38

1 ' Fig. 4.15: GradeBook.vb

2 ' GradeBook class with a property that performs validation.

3 Public Class GradeBook

4 Private courseNameValue As String ' course name for this GradeBook

5 6 ' constructor initializes CourseName with String supplied as argument

7 Public Sub New(ByVal name As String)

8 CourseName = name ' validate and store course name

9 End Sub ' New

10 11 ' property that gets and sets the course name; the Set accessor 12 ' ensures that the course name has at most 25 characters 13 Public Property CourseName() As String 14 Get ' retrieve courseNameValue 15 Return courseNameValue 16 End Get

Outline

GradeBook.vb

(1 of 3 )

• Suppose the system only allows course names of 25 characters or less.

• We now enhance class GradeBook’s property CourseName to perform this data validation (Fig. 4.15)

Fig. 4.15 | Method declarations for class GradeBook with aCourseName property that validates the length of instance

variable courseNameValue. (Part 1 of 3.)

Page 39: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

39

17 18 Set(ByVal value As String) ' set courseNameValue 19 If value.Length <= 25 Then ' if value has 25 or fewer characters 20 courseNameValue = value ' store the course name in the object 21 End If 22 23 If value.Length > 25 Then ' if value has more than 25 characters 24 ' set courseNameValue to first 25 characters of value 25 ' start at 0, length of 25 26 courseNameValue = value.Substring(0, 25) 27 28 Console.WriteLine( _ 29 "Name """ & value & """ exceeds maximum length (25).") 30 Console.WriteLine( _ 31 "Limiting course name to first 25 characters." & vbNewLine) 32 End If 33 End Set 34 End Property ' CourseName

Outline

GradeBook.vb

(2 of 3 )

This statement executes if value is valid

courseName is given a valid value

Substring returns part of an existing String.

To display double quotes in a string, you use two double quotes in a row.

Length returns the number of characters in the String.

Fig. 4.15 | Method declarations for class GradeBook with aCourseName property that validates the length of instance

variable courseNameValue. (Part 2 of 3.)

Page 40: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

40

35 36 ' display a welcome message to the GradeBook user 37 Public Sub DisplayMessage() 38 ' this statement uses property CourseName to get the 39 ' name of the course this GradeBook represents 40 Console.WriteLine("Welcome to the grade book for " _ 41 & vbNewLine & CourseName & "!") 42 End Sub ' DisplayMessage 43 End Class ' GradeBook

Outline

GradeBook.vb

(3 of 3 )

Fig. 4.15 | Method declarations for class GradeBook with aCourseName property that validates the length of instance

variable courseNameValue. (Part 3 of 3.)

Page 41: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

41

4.8 Validating Data with Set Accessors in Properties (Cont.)

• Length returns the number of characters in the String.

• Substring returns part of an existing String.• To display double quotes in a string, you use two

double quotes in a row.• The first 25 characters are assigned to courseNameValue to maintain a consistent state.

Page 42: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

42

1 ' Fig. 4.16: GradeBookTest.vb

2 ' Create and manipulate a GradeBook object; illustrate validation.

3 Module GradeBookTest

4 ' Main begins program execution

5 Sub Main()

6 ' create two GradeBook objects;

7 ' initial course name of gradeBook1 is too long

8 Dim gradeBook1 As New GradeBook( _

9 "CS101 Introduction to Visual Basic Programming")

10 Dim gradeBook2 As New GradeBook("CS102 VB Data Structures") 11 12 ' display each GradeBook's course name (by invoking Get) 13 Console.WriteLine("gradeBook1's initial course name is: " & _ 14 gradeBook1.CourseName) 15 Console.WriteLine("gradeBook2's initial course name is: " & _ 16 gradeBook2.CourseName) 17 Console.WriteLine() ' display blank line 18 19 ' place in gradeBook1's course name a valid-length String 20 gradeBook1.CourseName = "CS101 VB Programming" 21

Outline

GradeBookTest.vb

(1 of 3 )

• Testing the GradeBook object (Fig. 4.16).

Fig. 4.16 | Creating and manipulating a GradeBook object in which thecourse name is limited to 25 characters in length. (Part 1 of 2.)

Page 43: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

43

22 ' display each GradeBook's course name (by invoking Get) 23 Console.WriteLine( _ 24 "gradeBook1's course name is: " & gradeBook1.CourseName) 25 Console.WriteLine( _ 26 "gradeBook2's course name is: " & gradeBook2.CourseName) 27 End Sub ' Main 28 End Module ' GradeBookTest

Name "CS101 Introduction to Visual Basic Programming" exceeds maximum length (25).

Limiting course name to first 25 characters.

gradeBook1's initial course name is: CS101 Introduction to Vis

gradeBook2's initial course name is: CS102 VB Data Structures

gradeBook1's course name is: CS101 VB Programming

gradeBook2's course name is: CS102 VB Data Structures

Outline

GradeBookTest.vb

(2 of 3 )

Fig. 4.16 | Creating and manipulating a GradeBook object in which thecourse name is limited to 25 characters in length. (Part 2 of 2.)

Page 44: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

44Outline

GradeBookTest.vb

(3 of 3 )Error-Prevention Tip 4.2The benefits of data integrity are not automaticsimply because instance variables are madePrivate—you must provide appropriatevalidity checking and report the errors.

Error-Prevention Tip 4.3Set accessors that set the values of Privatedata should verify that the intended new valuesare proper; if they are not, the Set accessorsshould place the Private instance variables intoan appropriately consistent state.

Page 45: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

45

Fig. 4.17 | Nouns and noun phrases in the requirements document.

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document

Identifying the Classes in a System• Figure 4.17 lists the nouns in the requirements document.

Nouns and noun phrases in the requirements document

bank money / funds account number

ATM screen PIN

user keypad bank database

customer cash dispenser balance inquiry

transaction $20 bill / cash withdrawal

account deposit slot deposit

balance deposit envelope

Page 46: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

46

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

• We do not need to model “bank,” “user” or “customer” as a class, because they are not parts ofthe ATM system itself.

• We do not model “$20 bill” or “deposit envelope” as classes. These are physical objects in the real world, but they are not part of what is being automated.

• Monetary values are best represented as attributes. The account number and PIN represent attributes ofa bank account.

Page 47: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

47

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

• Each class is modeled as a rectangle with three compartments:

– Top compartment: name of the class.– Middle compartment: class’s attributes.– Bottom: class’s operations.

Fig. 4.18 | Representing a class in the UML using a class diagram.

Page 48: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

48

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)• Class diagrams also show the relationships between the classes

of the system (Fig. 4.19).– Hide class attributes and operations to create readable diagrams.

• currentTransaction is a role name for the Withdrawal object.

• An association is a relationship between classes.• Multiplicity values indicate how many objects of each class

participate in the association.

Fig. 4.19 | Class diagram showing an association among classes.

Page 49: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

49

Fig. 4.20 | Multiplicity types.

• The UML can model many types of multiplicity (Fig. 4.20).

Symbol Meaning

0 None

1 One

m An integer value

0..1 Zero or one

m, n m or n

m..n At least m, but not more than n

* Any nonnegative integer (zero or more)

0..* Zero or more (identical to *)

1..* One or more

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

Page 50: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

50

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

• In Fig. 4.21, the solid diamonds indicate that class ATM has a composition relationship.

• The class that has the composition symbol on its end of the association line is the whole, and the classes on the other end are the parts.

Fig. 4.21 | Class diagram showing composition relationships.

Page 51: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

51

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

• In the “has-a” relationship:– Only one class can represent the whole.– A part may belong to only one whole at a time, although the part

may be removed and attached to another whole.

• Hollow diamonds are used to indicate aggregation.– A personal computer “has a” monitor, but the two parts can exist

independently, and the monitor can be attached to multiple computers.

Page 52: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

52

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

• Figure 4.22 shows a class diagram.– ATM has a one-to-one relationship with class BankDatabase.– BankDatabase has a one-to-many relationship with class Account.

• Only the BankDatabase can access and manipulate an account directly.

Page 53: Introduction to Classes and Objects - Kent State …personal.kent.edu/~asamba/tech46330/Chap04.pdfWhat classes, objects, methods, instance variables and properties are. How to declare

2009 Pearson Education, Inc. All rights reserved.

53

4.9 Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.)

Fig. 4.22 | Class diagram for the ATM system model.