Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 9 9 Classes and Objects: A Deeper Look.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 9 9 Classes and Objects: A Deeper Look."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 9 9 Classes and Objects: A Deeper Look

2  2006 Pearson Education, Inc. All rights reserved. 2 Instead of this absurd division into sexes, they ought to class people as static and dynamic. — Evelyn Waugh Is it a world to hide virtues in? — William Shakespeare But what, to serve our private ends, Forbids the cheating of our friends? — Charles Churchill

3  2006 Pearson Education, Inc. All rights reserved. 3 Don’t be “consistent,” but be simply true. — Oliver Wendell Holmes, Jr. This above all: to thine own self be true. — William Shakespeare

4  2006 Pearson Education, Inc. All rights reserved. 4 OBJECTIVES In this chapter you will learn:  Encapsulation and data hiding.  The concepts of data abstraction and abstract data types (ADTs).  To use keyword this.  To use indexers to access members of a class.  To use static variables and methods.  To use readonly fields.  To take advantage of C# ’ s memory management features.  How to create a class library.  When to use the internal access modifier.

5  2006 Pearson Education, Inc. All rights reserved. 5 9.1 Introduction 9.2 Time Class Case Study 9.3 Controlling Access to Members 9.4 Referring to the Current Object’s Members with the this Reference 9.5 Indexers 9.6 Time Class Case Study: Overloaded Constructors 9.7 Default and Parameterless Constructors 9.8 Composition 9.9 Garbage Collection and Destructors 9.10 static Class Members 9.11 readonly Instance Variables 9.12 Software Reusability 9.13 Data Abstraction and Encapsulation 9.14 Time Class Case Study: Creating Class Libraries 9.15 internal Access 9.16 Class View and Object Browser 9.17 (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System 9.18 Wrap-Up

6  2006 Pearson Education, Inc. All rights reserved. 6 9.1 Introduction Object-Oriented Programming concepts and terminology Deeper look at building classes – Constructors static and readonly variables

7  2006 Pearson Education, Inc. All rights reserved. 7 9.2 Time Class Case Study public services (or public interface) – public methods available for a client to use If a class does not define a constructor the compiler will provide a default constructor Instance variables – Can be initialized when they are declared or in a constructor – Should maintain consistent (valid) values

8  2006 Pearson Education, Inc. All rights reserved. 8 Outline Time1.cs (1 of 2) private instance variables Declare public method setTime Validate parameter values before setting instance variables Format string

9  2006 Pearson Education, Inc. All rights reserved. 9 Outline Time1.cs (2 of 2) Format string

10  2006 Pearson Education, Inc. All rights reserved. 10 Software Engineering Observation 9.1 Methods and properties that modify the values of private variables should verify that the intended new values are proper. If they are not, they should place the private variables in an appropriate consistent state.

11  2006 Pearson Education, Inc. All rights reserved. 11 9.2 Time Class Case Study (Cont.) string ’s method Format – Returns a formatted string new implicitly invokes Time1 ’s default constructor since Time1 does not declare any constructors

12  2006 Pearson Education, Inc. All rights reserved. 12 Outline Time1Test.cs (1 of 2) Create a Time1 object Call ToUniversalString method Call ToString method Call SetTime method

13  2006 Pearson Education, Inc. All rights reserved. 13 Outline Time1Test.cs (2 of 2) Call SetTime method with invalid values

14  2006 Pearson Education, Inc. All rights reserved. 14 Software Engineering Observation 9.2 Classes simplify programming because the client can use only the public members exposed by the class. Such members are usually client oriented rather than implementation oriented. Clients are neither aware of, nor involved in, a class’s implementation. Clients generally care about what the class does but not how the class does it. (Clients do, of course, care that the class operates correctly and efficiently.)

15  2006 Pearson Education, Inc. All rights reserved. 15 Software Engineering Observation 9.3 Interfaces change less frequently than implementations. When an implementation changes, implementation-dependent code must change accordingly. Hiding the implementation reduces the possibility that other application parts will become dependent on class-implementation details.

16  2006 Pearson Education, Inc. All rights reserved. 16 9.3 Controlling Access to Members A class’s public interface – public methods is a view of the services the class provides to the class’s clients A class’s implementation details – private variables and private methods are not accessible to the class’s clients

17  2006 Pearson Education, Inc. All rights reserved. 17 Common Programming Error 9.1 An attempt by a method that is not a member of a class to access a private member of that class is a compilation error.

18  2006 Pearson Education, Inc. All rights reserved. 18 9.4 Referring to the Current Object’s Members with the this Reference The this reference – Any object can access a reference to itself with keyword this – Non- static methods implicitly use this when referring to the object’s instance variables and other methods – Can be used to access instance variables when they are shadowed by local variables or method parameters

19  2006 Pearson Education, Inc. All rights reserved. 19 Outline MemberAccessTest.cs Attempting to access private instance variables

20  2006 Pearson Education, Inc. All rights reserved. 20 Outline ThisTest.cs (1 of 2) Create new SimpleTime object Declare instance variables Method parameters shadow instance variables Using this to access the object’s instance variables

21  2006 Pearson Education, Inc. All rights reserved. 21 Outline ThisTest.cs (2 of 2) Using this explicitly and implicitly to call ToUniversalString Use of this not necessary here

22  2006 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 9.2 It is often a logic error when a method contains a parameter or local variable that has the same name as an instance variable of the class. In such a case, use reference this if you wish to access the instance variable of the class—otherwise, the method parameter or local variable will be referenced.

23  2006 Pearson Education, Inc. All rights reserved. 23 Error-Prevention Tip 9.1 Avoid method parameter names or local variable names that conflict with field names. This helps prevent subtle, hard-to-locate bugs.

24  2006 Pearson Education, Inc. All rights reserved. 24 Performance Tip 9.1 C# conserves memory by maintaining only one copy of each method per class—this method is invoked by every object of the class. Each object, on the other hand, has its own copy of the class’s instance variables (i.e., non- static variables). Each method of the class implicitly uses the this reference to determine the specific object of the class to manipulate.

25  2006 Pearson Education, Inc. All rights reserved. 25 9.5 Indexers Indexers – Class can use this keyword to define indexers that allow array- style indexed access to lists of elements in a class – Can define integer indices and non-integer indices – Syntax: accessModifier returnType this[ IndexType1 name1, IndexType2 name2, … ] { get { // use name1, name2,... here to get data } set { // use name1, name2,... here to set data } }

26  2006 Pearson Education, Inc. All rights reserved. 26 Common Programming Error 9.3 Declaring indexers as static is a syntax error.

27  2006 Pearson Education, Inc. All rights reserved. 27 Outline Box.cs (1 of 3)

28  2006 Pearson Education, Inc. All rights reserved. 28 Outline Box.cs (2 of 3) Indexer for dimensions Validations

29  2006 Pearson Education, Inc. All rights reserved. 29 Outline Box.cs (3 of 3) Indexer for names Locate elements

30  2006 Pearson Education, Inc. All rights reserved. 30 Outline BoxTest.cs (1 of 2) Output dimensions with indexers

31  2006 Pearson Education, Inc. All rights reserved. 31 Outline BoxTest.cs (2 of 2) Setting using indexers Output names with indexers

32  2006 Pearson Education, Inc. All rights reserved. 32 9.6 Time Class Case Study: Overloaded Constructors Overloaded constructors – Provide multiple constructor definitions with different signatures No-argument constructor – A constructor invoked without arguments The this reference can be used to invoke another constructor

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline Time2.cs (1 of 4) No-argument constructor Invoke three-argument constructor Call SetTime method Constructor takes a reference to another Time2 object as a parameter

34  2006 Pearson Education, Inc. All rights reserved. 34 Outline Time2.cs (2 of 4) Only members of this class use the set part of this property to change the hour Validation

35  2006 Pearson Education, Inc. All rights reserved. 35 Outline Time2.cs (3 of 4) Only members of this class use the set part of this property to change the minute Validation Only members of this class use the set part of this property to change the second Validation

36  2006 Pearson Education, Inc. All rights reserved. 36 Outline Time2.cs (4 of 4)

37  2006 Pearson Education, Inc. All rights reserved. 37 Common Programming Error 9.4 A constructor can call methods of the class. Be aware that the instance variables might not yet be in a consistent state, because the constructor is in the process of initializing the object. Using instance variables before they have been initialized properly is a logic error.

38  2006 Pearson Education, Inc. All rights reserved. 38 Software Engineering Observation 9.4 When one object of a class has a reference to another object of the same class, the first object can access all the second object’s data and methods (including those that are private ).

39  2006 Pearson Education, Inc. All rights reserved. 39 Software Engineering Observation 9.5 When implementing a method of a class, use the class’s properties to access the class’s private data. This simplifies code maintenance and reduces the likelihood of errors.

40  2006 Pearson Education, Inc. All rights reserved. 40 9.7 Default and Parameterless Constructors Every class must have at least one constructor – If no constructors are declared, the compiler will create a default constructor Takes no arguments and initializes instance variables to their initial values specified in their declaration or to their default values - Default values are zero for primitive numeric types, false for boolean values and null for references – If constructors are declared, the compiler will not create a default constructor

41  2006 Pearson Education, Inc. All rights reserved. 41 Outline Time2Test.cs (1 of 3) Call overloaded constructors

42  2006 Pearson Education, Inc. All rights reserved. 42 Outline Time2Test.cs (2 of 3)

43  2006 Pearson Education, Inc. All rights reserved. 43 Outline Time2Test.cs (3 of 3)

44  2006 Pearson Education, Inc. All rights reserved. 44 Common Programming Error 9.5 If a class has constructors, but none of the public constructors are parameterless constructors, and an application attempts to call a parameterless constructor to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if the class does not have any constructors (in which case the default constructor is called) or if the class has a public parameterless constructor.

45  2006 Pearson Education, Inc. All rights reserved. 45 Common Programming Error 9.6 Only constructors can have the same name as the class. Declaring a method, property or field with the same name as the class is a compilation error.

46  2006 Pearson Education, Inc. All rights reserved. 46 9.8 Composition Composition – A class can have references to objects of other classes as members – Sometimes referred to as a has-a relationship

47  2006 Pearson Education, Inc. All rights reserved. 47 Software Engineering Observation 9.6 One form of software reuse is composition, in which a class has as members references to objects of other classes.

48  2006 Pearson Education, Inc. All rights reserved. 48 Outline Date.cs (1 of 5)

49  2006 Pearson Education, Inc. All rights reserved. 49 Outline Date.cs (2 of 5)

50  2006 Pearson Education, Inc. All rights reserved. 50 Outline Date.cs (3 of 5) Validates month value

51  2006 Pearson Education, Inc. All rights reserved. 51 Outline Date.cs (4 of 5) Validates day value

52  2006 Pearson Education, Inc. All rights reserved. 52 Outline Date.cs (5 of 5)

53  2006 Pearson Education, Inc. All rights reserved. 53 Outline Employee.cs Employee contains references to two Date objects Implicit calls to hireDate and birthDate ’s ToString methods

54  2006 Pearson Education, Inc. All rights reserved. 54 Outline EmployeeTest.cs Create an Employee object Display the Employee object

55  2006 Pearson Education, Inc. All rights reserved. 55 9.9 Garbage Collection and Destructors Garbage Collection – Automatic memory management that reclaim the memory occupied by objects no longer in use – Not guaranteed to perform its task at specified time Destructor – Object eligible for destruction when there is no more reference to that object – Invoked by garbage collector before reclaiming object’s memory – Declared like a parameterless constructor preceded by tilda (~)

56  2006 Pearson Education, Inc. All rights reserved. 56 Software Engineering Observation 9.7 A class that uses system resources, such as files on disk, should provide a method to eventually release the resources. Many FCL classes provide Close or Dispose methods for this purpose.

57  2006 Pearson Education, Inc. All rights reserved. 57 9.10 static Class Members static variables – Represents class-wide information – Used when: all objects of the class should share the same copy of this instance variable The instance variable should be accessible even when no objects of the class exist – Can be accessed with the class name or an object name and a dot (. ) – Must be initialized in their declarations, or else the compiler will initialize it with a default value ( 0 for int s)

58  2006 Pearson Education, Inc. All rights reserved. 58 Software Engineering Observation 9.8 Use a static variable when all objects of a class must use the same copy of the variable.

59  2006 Pearson Education, Inc. All rights reserved. 59 Common Programming Error 9.7 It is a compilation error to access or invoke a static member by referencing it through an instance of the class, like a non- static member.

60  2006 Pearson Education, Inc. All rights reserved. 60 Software Engineering Observation 9.9 Static variables and methods exist, and can be used, even if no objects of that class have been instantiated.

61  2006 Pearson Education, Inc. All rights reserved. 61 Outline Employee.cs (1 of 3) Declare a static field Increment static field

62  2006 Pearson Education, Inc. All rights reserved. 62 Outline Employee.cs (2 of 3) Declare a destructor

63  2006 Pearson Education, Inc. All rights reserved. 63 Outline Employee.cs (3 of 3) Declare static property Count to get static field count

64  2006 Pearson Education, Inc. All rights reserved. 64 9.10 static Class Members (Cont.) String objects are immutable – String concatenation operations actually result in the creation of a new String object Garbage Collection – static method Collect of class GC Indicates that the garbage collector should make a best-effort attempt to reclaim objects eligible for garbage collection It is possible that no objects or only a subset of eligible objects will be collected – static method WaitForPendingFinalizers of class GC Stops execution of the Main until all destructors finish executing static methods cannot access non- static class members – Also cannot use the this reference

65  2006 Pearson Education, Inc. All rights reserved. 65 Outline EmployeeTest.cs (1 of 3) Create new Employee objects Call static property Count using class name Employee

66  2006 Pearson Education, Inc. All rights reserved. 66 Outline EmployeeTest.cs (2 of 3) Remove references to objects, CLR will mark them for garbage collection Call static method Collect of class GC to indicate that garbage collection should be attempted Call static property Count using class name Employee

67  2006 Pearson Education, Inc. All rights reserved. 67 Outline EmployeeTest.cs (3 of 3)

68  2006 Pearson Education, Inc. All rights reserved. 68 Common Programming Error 9.8 A compilation error occurs if a static method calls an instance (non- static ) method in the same class by using only the method name. Similarly, a compilation error occurs if a static method attempts to access an instance variable in the same class by using only the variable name.

69  2006 Pearson Education, Inc. All rights reserved. 69 Common Programming Error 9.9 Referring to the this reference in a static method is a syntax error.

70  2006 Pearson Education, Inc. All rights reserved. 70 9.11 readonly Instance Variables readonly – Specify that an instance variable of an object is not modifiable – Can be initialized when declared or inside constructor – If not initialized, then default values are assigned

71  2006 Pearson Education, Inc. All rights reserved. 71 Software Engineering Observation 9.10 Declaring an instance variable as readonly helps enforce the principle of least privilege. If an instance variable should not be modified after the object is constructed, declare it to be readonly to prevent modification.

72  2006 Pearson Education, Inc. All rights reserved. 72 Common Programming Error 9.10 Attempting to modify a readonly instance variable anywhere but its declaration or the object’s constructors is a compilation error.

73  2006 Pearson Education, Inc. All rights reserved. 73 Error-Prevention Tip 9.2 Attempts to modify a readonly instance variable are caught at compilation time rather than causing execution-time errors. It is always preferable to get bugs out at compile time, if possible, rather than allowing them to slip through to execution time (where studies have found that repairing is often many times more costly).

74  2006 Pearson Education, Inc. All rights reserved. 74 Outline Increment.cs Declare readonly instance variable Initialize readonly instance variable inside a constructor

75  2006 Pearson Education, Inc. All rights reserved. 75 Outline IncrementTest.cs Create an Increment object Call method AddIncrementToTotal

76  2006 Pearson Education, Inc. All rights reserved. 76 Software Engineering Observation 9.11 If a readonly instance variable is initialized to a constant only in its declaration, it is not necessary to have a separate copy of the instance variable for every object of the class. The variable should be declared const instead. Constants declared with const are implicitly static, so there will only be one copy for the entire class.

77  2006 Pearson Education, Inc. All rights reserved. 77 9.12 Software Reusability Rapid application development (RAD) – Software reusability speeds the development of powerful, high-quality software.NET Framework Class Library – Programmers can focus on task at hand and leave the lower-level details to classes of the FCL – Programmers to bring new applications faster by using preexisting components – msdn2.microsoft.com/en-us/library/ms229335

78  2006 Pearson Education, Inc. All rights reserved. 78 Good Programming Practice 9.1 Avoid reinventing the wheel. Study the capabilities of the FCL. If the FCL contains a class that meets your application’s requirements, use that class rather than create your own.

79  2006 Pearson Education, Inc. All rights reserved. 79 9.13 Data Abstraction and Encapsulation Data abstraction – Information hiding Classes normally hide the details of their implementation from their clients – Abstract data types (ADTs) Data representation - example: primitive type int is an abstract representation of an integer int s are only approximations of integers, can produce arithmetic overflow Operations that can be performed on data

80  2006 Pearson Education, Inc. All rights reserved. 80 Software Engineering Observation 9.12 Programmers create types through the class mechanism. New types can be designed to be as convenient to use as the simple types. This marks C# as an extensible language. Although the language is easy to extend via new types, the programmer cannot alter the base language itself.

81  2006 Pearson Education, Inc. All rights reserved. 81 9.13 Data Abstraction and Encapsulation (Cont.) Queues – Similar to a “waiting line” Clients place items in the queue (enqueue an item) Clients get items back from the queue (dequeue an item) First-in, first out (FIFO) order – Internal data representation is hidden Clients only see the ability to enqueue and dequeue items

82  2006 Pearson Education, Inc. All rights reserved. 82 9.14 Time Class Case Study: Creating Class Libraries Steps for Declaring and Using a Reusable Class – Declare a public class – Choose a namespace name and add a namespace declaration to the source-code file for the reusable class (Fig. 9.16) – Compile the class into a class library (Fig. 9.17) – Add a reference to the class library in an application (Fig. 9.18) – Specify a using directive for the namespace of the reusable class (Fig. 9.19)

83  2006 Pearson Education, Inc. All rights reserved. 83 Outline Time1.cs (1 of 2) namespace declaration Time1 is a public class so it can be used by importers of this namespace

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

85  2006 Pearson Education, Inc. All rights reserved. 85 Fig. 9.17 | Creating a Class Library Project.

86  2006 Pearson Education, Inc. All rights reserved. 86 Fig. 9.18 | Adding a Reference.

87  2006 Pearson Education, Inc. All rights reserved. 87 Outline Time1NamespaceTest.cs (1 of 2) Uses the Chapter09 namespace

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

89  2006 Pearson Education, Inc. All rights reserved. 89 9.15 internal Access internal – If there are no access modifier than defaults to internal – Allows the class to be used by all code in the same assembly Within the same assembly, this is equivalent to public

90  2006 Pearson Education, Inc. All rights reserved. 90 Outline InternalAccessTest.cs (1 of 2) Accesses internal instance variables directly

91  2006 Pearson Education, Inc. All rights reserved. 91 Outline InternalAccessTest.cs (2 of 2) Declaration of internal instance variables

92  2006 Pearson Education, Inc. All rights reserved. 92 9.16 Class View and Object Browser Two features of Visual Studio to facilitate object- oriented applications – Class View Window (Fig. 9.21) Display the fields and methods for all classes in project When a class is selected, the class’s members are shown on the lower half of the window – Object Browser (Fig. 9.22) Lists all classes in the C# library (left frame) - Learn the functionality provided by specific classes Methods provided on the upper-right frame Description of members appears in the lower-right frame

93  2006 Pearson Education, Inc. All rights reserved. 93 Fig. 9.21 | Class View of class Time1 (Fig. 9.1) and class TimeTest (Fig. 9.2).

94  2006 Pearson Education, Inc. All rights reserved. 94 Fig. 9.22 | Object Browser for class Math.

95  2006 Pearson Education, Inc. All rights reserved. 95 9.17 Software Engineering Case Study: Starting to Program the Classes of the ATM System Visibility – Attributes normally should be private, methods invoked by clients should be public – Visibility markers in UML A plus sign (+) indicates public visibility A minus sign (-) indicates private visibility Navigability – Navigability arrows indicate in which direction an association can be traversed – Bidirectional navigability Associations with navigability arrows at both ends or no navigability arrows at all can be traversed in either direction

96  2006 Pearson Education, Inc. All rights reserved. 96 Fig. 9.23 | Class diagram with visibility markers.

97  2006 Pearson Education, Inc. All rights reserved. 97 Fig. 9.24 | Class diagram with navigability arrows.

98  2006 Pearson Education, Inc. All rights reserved. 98 9.17 Software Engineering Case Study: Starting to Program the Classes of the ATM System (Cont.) Implementing the ATM system from its UML design (for each class) – Declare a public class with the name in the first compartment and an empty no-argument constructor – Declare instance variables based on attributes in the second compartment – Declare references to other objects based on associations described in the class diagram – Declare the shells of the methods based on the operations in the third compartment Use the return type void if no return type has been specified

99  2006 Pearson Education, Inc. All rights reserved. 99 Outline Withdrawal.cs Class for Withdrawal Empty no-argument constructor

100  2006 Pearson Education, Inc. All rights reserved. 100 Outline Withdrawal.cs Declare instance variables

101  2006 Pearson Education, Inc. All rights reserved. 101 Outline Withdrawal.cs Declare references to other objects

102  2006 Pearson Education, Inc. All rights reserved. 102 Outline Account.cs Declare shell of a method with return type void

103  2006 Pearson Education, Inc. All rights reserved. 103 Software Engineering Observation 9.13 Many UML modeling tools can convert UML- based designs into C# code, considerably speeding up the implementation process. For more information on these “automatic” code generators, refer to the Web resources listed at the end of Section 3.10.

104  2006 Pearson Education, Inc. All rights reserved. 104 Outline Account.cs (1 of 2) Declare properties for the instance variables

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


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 9 9 Classes and Objects: A Deeper Look."

Similar presentations


Ads by Google