Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 4 4 Introduction to Classes and Objects.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 4 4 Introduction to Classes and Objects."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 4 4 Introduction to Classes and Objects

2  2006 Pearson Education, Inc. All rights reserved. 2 Your public servants serve you right. — Adlai E. Stevenson Nothing can have value without being an object of utility. — Karl Marx Knowing how to answer one who speaks, To reply to one who sends a message. — Amenemope You will see something new. Two things. And I call them Thing One and Thing Two. — Dr. Theodor Seuss Geisel

3  2006 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn:  What classes, objects, methods and instance variables 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 the methods perform their tasks.  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 data is initialized when the object is created.  The differences between value types and reference types.

4  2006 Pearson Education, Inc. All rights reserved. 4 4.1 Introduction 4.2 Classes, Objects, Methods, Properties and Instance Variables 4.3 Declaring a Class with a Method and Instantiating an Object of a Class 4.4 Declaring a Method with a Parameter 4.5 Instance Variables and Properties 4.6 UML Class Diagram with a Property 4.7 Software Engineering with Properties and set and get Accessors 4.8 Value Types vs. Reference Types 4.9 Initializing Objects with Constructors 4.10 Floating-Point Numbers and Type decimal 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document 4.12 Wrap-Up

5  2006 Pearson Education, Inc. All rights reserved. 5 4.1 Introduction Classes ─Properties ─Methods ─Constructors Floating-Point Numbers

6  2006 Pearson Education, Inc. All rights reserved. 6 4.2 Classes, Objects, Methods, Properties and Instance Variables Class provides one or more methods Method represents task in a program ─Describes the mechanisms that actually perform its tasks ─Hides from its user the complex tasks that it performs ─Method call tells method to perform its task Classes contain one or more attributes ─Specified by instance variables ─Carried with the object as it is used

7  2006 Pearson Education, Inc. All rights reserved. 7 4.3 Declaring a Class with a Method and Instantiating an Object of a Class Class GradeBook ─Keyword public is an access modifier ─Class declarations include: Access modifier Keyword class Pair of left and right braces

8  2006 Pearson Education, Inc. All rights reserved. 8 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Class GradeBook ─Method declarations Keyword public indicates method is available to the public Keyword void indicates that there is no return type Methods without void return results Access modifier, return type, name of method and parentheses comprise method header Naming convention is to capitalize the first letter of every word

9  2006 Pearson Education, Inc. All rights reserved. 9 Outline GradeBook.cs The method header for DisplayMessage()

10  2006 Pearson Education, Inc. All rights reserved. 10 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Class GradeBookTest ─Any class that contains a Main method can be used to execute an application ─ static method is special because it can be called without first creating object of the class ─C# is extensible Programmers can create new classes ─Class instance creation expression Keyword new Then name of class to create and parentheses ─Calling a method Object’s name, then dot separator (. ) Then method’s name and parentheses

11  2006 Pearson Education, Inc. All rights reserved. 11 Outline GradeBookTest.cs Use class instance creation expression to create object of class GradeBook Call method DisplayMessage using GradeBook object

12  2006 Pearson Education, Inc. All rights reserved. 12 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) UML class diagrams (Fig. 4.3) ─Top compartment contains name of the class ─Middle compartment contains class’s attributes or instance variables ─Bottom compartment contains class’s operations or methods Plus sign indicates public methods

13  2006 Pearson Education, Inc. All rights reserved. 13 Fig. 4.3 | UML class diagram indicating that class GradeBook has a public DisplayMessage operation.

14  2006 Pearson Education, Inc. All rights reserved. 14 4.4 Declaring a Method with a Parameter Method parameters (Fig. 4.4) ─Additional information passed to a method ─Supplied in the method call with arguments Input method (Fig. 4.5) ─ Console.ReadLine reads a line of input

15  2006 Pearson Education, Inc. All rights reserved. 15 Outline GradeBook.cs Method header DisplayMessage that takes a courseName argument of type string

16  2006 Pearson Education, Inc. All rights reserved. 16 Outline GradeBookTest.cs Call ReadLine method to read a line of input and assigns it to nameOfCourse Call DisplayMessage with an argument

17  2006 Pearson Education, Inc. All rights reserved. 17 Software Engineering Observation 4.1 Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as " hello ". String literals are references to string objects that are implicitly created by C#.

18  2006 Pearson Education, Inc. All rights reserved. 18 4.4 Declaring a Method with a Parameter (Cont.) Parameters specified in method’s parameter list ─Part of method header ─Uses a comma-separated list UML class diagram (Fig. 4.6) ─Parameters specified by parameter name followed by a colon and parameter type

19  2006 Pearson Education, Inc. All rights reserved. 19 Common Programming Error 4.1 A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration.

20  2006 Pearson Education, Inc. All rights reserved. 20 Common Programming Error 4.2 A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

21  2006 Pearson Education, Inc. All rights reserved. 21 Fig. 4.6 | UML class diagram indicating that class GradeBook has a public DisplayMessage operation with a courseName parameter of type string.

22  2006 Pearson Education, Inc. All rights reserved. 22 4.4 Declaring a Method with a Parameter (Cont.) Using Directives ─Indicts to the compiler that the application uses classes in a namespace ─By default, classes complied in same project is considered in the same namespace ─Any classes not explicitly placed in a namespace are implicitly placed in the global namespace.

23  2006 Pearson Education, Inc. All rights reserved. 23 4.5 Instance Variables and Properties Variables declared in the body of method ─Called local variables ─Can only be used within that method Variables declared in a class declaration ─Called fields or instance variables ─Each object of the class has a separate instance of the variable

24  2006 Pearson Education, Inc. All rights reserved. 24 Outline GradeBook.cs (1 of 2) Instance variable courseName get accessor for property courseName set accessor for property courseName

25  2006 Pearson Education, Inc. All rights reserved. 25 Outline GradeBook.cs (2 of 2) Call the get accessor

26  2006 Pearson Education, Inc. All rights reserved. 26 4.5 Instance Variables and Properties (Cont.) private keyword ─Used for most instance variables ─ private variables and methods are accessible only to methods of the class in which they are declared ─Declaring instance variables private is known as information hiding

27  2006 Pearson Education, Inc. All rights reserved. 27 Software Engineering Observation 4.2 Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods and properties should be declared public. If the access modifier is omitted before a member of a class, the member is implicitly declared private by default. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

28  2006 Pearson Education, Inc. All rights reserved. 28 Good Programming Practice 4.1 We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class’s fields anywhere in the class outside its method declarations, but scattering them can make code difficult to read.

29  2006 Pearson Education, Inc. All rights reserved. 29 Good Programming Practice 4.2 Placing a blank line between method and property declarations enhances application readability.

30  2006 Pearson Education, Inc. All rights reserved. 30 4.5 Instance Variables and Properties (Cont.) Property Declaration ─Declaration consist of an access modifier, type, and name ─ get and set allows you to access and modify private variables outside of the class, respectively ─Contain a get accessor, set accessor, or both ─After defining a property, you can use it like a variable get and set Accessors ─ get accessor contains a return statement ─ set accessor contains a variable = value value implicitly declared

31  2006 Pearson Education, Inc. All rights reserved. 31 4.5 Instance Variables and Properties (Cont.) Default initial value ─Provided for all fields not initialized 0 for numeric/value type variables null for String s and reference types

32  2006 Pearson Education, Inc. All rights reserved. 32 Outline GradeBookTest.cs (1 of 2) Call get accessor of CourseName Call set accessor of CourseName

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline GradeBookTest.cs (2 of 2) Call DisplayMessage

34  2006 Pearson Education, Inc. All rights reserved. 34 4.6 UML Class Diagram with Property UML Diagram ─Model properties in the UML as attributes: Public is indicated by the “+” sign > Property’s name “:” property’s type ─Modeling private instance variables that are not properties: Attribute’s name “:” attribute’s type Private is indicated by the “-” sign

35  2006 Pearson Education, Inc. All rights reserved. 35 Fig. 4.9 | UML class diagram indicating that class GradeBook has a public CourseName property of type string and one public method.

36  2006 Pearson Education, Inc. All rights reserved. 36 4.7 Software Engineering with Properties and set and get Accessors Public variable can be read or written by any property or method Private variables can only be access indirectly through the class’s non-private properties ─Class able to control how the data is set or returned ─Allows for data validation Properties of a class should use class’s own methods to manipulate the class’s private instance variables ─Creates more robust class

37  2006 Pearson Education, Inc. All rights reserved. 37 Software Engineering Observation 4.3 Accessing 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 performance), only the properties’ implementations need to change—the clients’ implementations need not change as long as the services provided by the properties are preserved.

38  2006 Pearson Education, Inc. All rights reserved. 38 4.8 Value Types vs. Reference Types Types in C# ─Value (Simple Types except String ) Contains a value of that type List of Simple Types in Appendix L ─Reference (sometimes called non-simple types) Objects Default value of null Used to invoke an object’s methods and properties

39  2006 Pearson Education, Inc. All rights reserved. 39 Fig. 4.10 | Value type variable.

40  2006 Pearson Education, Inc. All rights reserved. 40 Fig. 4.11 | Reference type variable.

41  2006 Pearson Education, Inc. All rights reserved. 41 Software Engineering Observation 4.4 A variable’s declared type (e.g., int, double or GradeBook ) indicates whether the variable is of a value or a reference type. If a variable’s type is not one of the thirteen simple types, or an enum or a struct type (which we discuss in Section 7.10 and Chapter 16, respectively), then it is a reference type. For example, Account account1 indicates that account1 is a variable that can refer to an Account object.

42  2006 Pearson Education, Inc. All rights reserved. 42 4.9 Initializing Objects with Constructors Constructors ─Initialize an object of a class ─Visual Basic requires a constructor for every class ─Visual Basic will provide a default no-argument constructor ONLY when none is provided ─Called when keyword new is followed by the class name and parentheses ─Constructors can also take arguments ─Constructor header similar to regular method header except the name is always the class name

43  2006 Pearson Education, Inc. All rights reserved. 43 Outline GradeBook.cs (1 of 2) Constructor to initialize courseName variable

44  2006 Pearson Education, Inc. All rights reserved. 44 Outline GradeBook.cs (2 of 2)

45  2006 Pearson Education, Inc. All rights reserved. 45 Outline GradeBookTest.cs (1 of 2) Call constructor to create first grade book object Create second grade book object

46  2006 Pearson Education, Inc. All rights reserved. 46 Outline GradeBookTest.cs (2 of 2)

47  2006 Pearson Education, Inc. All rights reserved. 47 4.9 Initializing Objects with Constructors (Cont.) UML class diagram ─Constructors go in third compartment ─Place “ >” before constructor name and its arguments ─By convention, place constructors first in their compartment

48  2006 Pearson Education, Inc. All rights reserved. 48 Error-Prevention Tip 4.1 Unless default initialization of your class’s instance variables is acceptable, provide a constructor to ensure that your class’s instance variables are properly initialized with meaningful values when each new object of your class is created.

49  2006 Pearson Education, Inc. All rights reserved. 49 Fig. 4.14 | UML class diagram indicating that class GradeBook has a constructor with a name parameter of type string.

50  2006 Pearson Education, Inc. All rights reserved. 50 4.10 Floating-Point Numbers and Type decimal Floating-point numbers (Approximations) ─ float (Single-Precision) ─ double (Double-Precision) Stores numbers with greater magnitude and precision than float decimal ─Stores a limited range of real numbers precisely

51  2006 Pearson Education, Inc. All rights reserved. 51 Common Programming Error 4.3 Using floating-point numbers in a manner that assumes they are represented precisely can lead to logic errors.

52  2006 Pearson Education, Inc. All rights reserved. 52 4.10 Floating-Point Numbers and Type decimal (Cont.) float ─Single-precision floating-point numbers ─7 significant digits double ─Double-precision floating-point numbers ─15 significant digits decimal ─29 significant digits ─ decimal literal: Must type “M” or “m” after number

53  2006 Pearson Education, Inc. All rights reserved. 53 Outline Account.cs (1 of 2) Private decimal variable balance decimal should be used for monetary numbers

54  2006 Pearson Education, Inc. All rights reserved. 54 Outline Account.cs (2 of 2) set property validation

55  2006 Pearson Education, Inc. All rights reserved. 55 Outline AccountTest.cs (1 of 2) Used to format currency output

56  2006 Pearson Education, Inc. All rights reserved. 56 Outline AccountTest.cs (2 of 2)

57  2006 Pearson Education, Inc. All rights reserved. 57 4.10 Floating-Point Numbers and Type decimal (Cont.) Format specifier {0: C} ─Used to output monetary amount (currency) ─Other format specifier by placing certain letters after the colon. (List of these letters in Fig. 4.17)

58  2006 Pearson Education, Inc. All rights reserved. 58 Fig. 4.17 | string format specifiers.

59  2006 Pearson Education, Inc. All rights reserved. 59 Error-Prevention Tip 4.2 The benefits of data integrity are not automatic simply because instance variables are made private —you must provide appropriate validity checking and report the errors.

60  2006 Pearson Education, Inc. All rights reserved. 60 Error-Prevention Tip 4.3 set accessors that set the values of private data should verify that the intended new values are proper; if they are not, the set accessors should leave the instance variables unchanged and generate an error. We demonstrate how to gracefully generate errors in Chapter 12, Exception Handling.

61  2006 Pearson Education, Inc. All rights reserved. 61 Fig. 4.18 | UML class diagram indicating that class Account has a public Balance property of type decimal, a constructor and a method.

62  2006 Pearson Education, Inc. All rights reserved. 62 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document Begin designing the ATM system ─Analyze the nouns and noun phrases ─Introduce UML class diagrams

63  2006 Pearson Education, Inc. All rights reserved. 63 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.) Key nouns and noun phrases in requirements document ─Some are attributes of other classes ─Some do not correspond to parts of the system ─Some are classes To be represented by UML class diagrams

64  2006 Pearson Education, Inc. All rights reserved. 64 Fig. 4.19 | Nouns and noun phrases in the requirements document.

65  2006 Pearson Education, Inc. All rights reserved. 65 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.) UML class diagrams ─Top compartment contains name of the class ─Middle compartment contains class’s attributes or instance variables ─Bottom compartment contains class’s operations or methods

66  2006 Pearson Education, Inc. All rights reserved. 66 Fig. 4.20 | Representing a class in the UML using a class diagram.

67  2006 Pearson Education, Inc. All rights reserved. 67 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.) UML class diagrams ─Allows suppression of class attributes and operations Called an elided diagram ─Solid line that connects two classes represents an association numbers near end of each line are multiplicity values

68  2006 Pearson Education, Inc. All rights reserved. 68 Fig. 4.21 | Class diagram showing an association among classes.

69  2006 Pearson Education, Inc. All rights reserved. 69 Fig. 4.22 | Multiplicity types.

70  2006 Pearson Education, Inc. All rights reserved. 70 4.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Document (Cont.) UML class diagrams ─Solid diamonds attached to association lines indicate a composition relationship ─Hollow diamonds indicate aggregation – a weaker form of composition

71  2006 Pearson Education, Inc. All rights reserved. 71 Fig. 4.23 | Class diagram showing composition relationships.

72  2006 Pearson Education, Inc. All rights reserved. 72 Fig. 4.24 | Class diagram for the ATM system model.

73  2006 Pearson Education, Inc. All rights reserved. 73 Fig. 4.25 | Class diagram showing some composition relationships of a class Car.

74  2006 Pearson Education, Inc. All rights reserved. 74 Fig. 4.26 | Class diagram for the ATM system model including class Deposit.


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 4 4 Introduction to Classes and Objects."

Similar presentations


Ads by Google