Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz, 2015 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. ©1992-2014 by Pearson Education, Inc.

Similar presentations


Presentation on theme: "Jozef Goetz, 2015 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. ©1992-2014 by Pearson Education, Inc."— Presentation transcript:

1

2 Jozef Goetz, 2015 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. ©1992-2014 by Pearson Education, Inc. All Rights Reserved.

3 Jozef Goetz, 2015 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  This above all: to thine own self be true.  William Shakespeare  Don’t be “consistent,” but be simply true.  Oliver Wendell Holmes, Jr.

4 Jozef Goetz, 2015 3 Outline: 10.1 Introduction 10.2 Time Class Case Study 10.3 Controlling Access to Members 10.4 Referring to the Current Object’s Members with the this Reference 10.5 Time Class Case Study: Overloaded Constructors 10.6 Default and Parameterless Constructors 10.7 Composition 10.8 Garbage Collection and Destructors 10.9 static Class Members 10.10 readonly Instance Variables 10.11 Data Abstraction and Encapsulation 10.12 Class View and Object Browser 10.13 Object Initializers Chapter 10 – Classes and Objects Classes and Objects Objectives  To understand encapsulation and data hiding.  To understand the concepts of data abstraction and abstract data types (ADTs).  To be able to create, use and destroy objects.  To be able to control access to object instance variables and methods.  To be able to use properties to keep objects in consistent states.  To use object initializers to set property values as you create a new object.  To understand the use of the this reference.  To understand namespaces and assemblies.  To be able to use the Class View and Object Browser.

5 Jozef Goetz, 2015 4 10.1 Introduction  Object-based programming (OBP)  Object classes encapsulate (wrap together) data (attributes, or member variable or instance variables) and methods (behavior) into packages called classes  Data and methods closely related  Object-oriented programming (next chapters)  Using inheritance and polymorphism – key features that enable true OOP  Unit of C is the function (method)  Unit of C# (and Java programming): the class

6 Jozef Goetz, 2015 5 Two Programming Methodologies Functional Object-Oriented Decomposition Design FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT Operations Data

7 Jozef Goetz, 2015 6 What is an object? OBJECT Operations Data set of functions internal state

8 Jozef Goetz, 2015 7 10.1 Introduction - class  class  The opening left brace ({) and closing right brace (}) delimit the body of a class  A class is like a blueprint – reusable  Implementation details are hidden within the classes  Objects are instantiated (created) from the class  Allows objects to communicate  Well-defined interfaces (services) are public methods  a class can yield many objects, just as a primitive data type, such as int, can yield many variables  classes simplify programming because the client of a class need to use only the public operations (method / services) encapsulated in the object  without knowing the internal details of how the class is implemented

9 Jozef Goetz, 2015 8 OOD Specification (ADT) and Implementation in C++ clockType.h client.cpp clockType.cpp client.obj client.execlockType.obj Compiler Linker #include “clockType.h” implementation file specification file main (user) program cc –c client.cpp link

10 Jozef Goetz, 2015 9  Abstract Data Types (ADT) – hides implementation from other objects  change the internal implementation of that class without affecting the clients of that class  in procedural languages: the client code often is dependent on implementation details of the data used in the code  Variables inside the class definition (outside methods) but not a method definition are called instance variables  Member Access Modifiers  public : member is accessible wherever an instance of the object exists  private : member is accessible only inside that class definition 10.2 Implementing a Time Abstract Data Type with a Class

11 Jozef Goetz, 2015 10 10.2 Implementing a Time Abstract Data Type with a Class  Access methods (assessors get and set) : read or write data  Predicate methods : test the truth of conditions  IsEmpty(), IsFull()  Utility (helper) methods  private methods that support access methods  Methods should perform only one task  If a method needs to perform another task to calculate its result, it should use a helper method  The client should not have access to helper methods, thus they should be declared private

12 Jozef Goetz, 2015 11 10.2 Implementing a Time Abstract Data Type with a Class  Constructor: 1.Declared public 2.Initializes objects of the class –Operator new used to instantiate classes 3.Must have the same name as the class name 4.Can take arguments 5.Cannot return values 6.There may be more then one constructor per class (overloaded constructors)  Use Project => Add Class to add a new class to your project Time1 time = new Time1();

13 Jozef Goetz, 2015 12 10.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

14 Jozef Goetz, 2015 13  We introduce classes Time1 and TimeTest in separate files  Time1.cs defines class Time1  Our non-application, class  TimeTest1.cs defines class TimeTest1  public classes must be defined in separate files  Only one public class per file  Class Time1 will not execute by itself  Does not have method main  TimeTest, which has method Main, creates (instantiates) and uses Time1 object 10.2 Implementing a Time Abstract Data Type with a Class

15  2002 Prentice Hall. All rights reserved. Outline 14 Time1.cs 1 // Fig. 10.1: Time1.cs Time ADT 2 // Class Time1 maintains time in 24-hour format. 3 4 using System; // it doesn’t import the namespace that contains class Time1, because the default name space include all classes in the current directory 5 6 // Time1 class definition 7 public class Time1 : Object 8 { // instance variables: 9 private int hour; // 0-23 10 private int minute; // 0-59 11 private int second; // 0-59 12 13 // Time1 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time1() 16 { 17 SetTime( 0, 0, 0 ); 18 } 19 20 // Set new time value in 24-hour format. Perform validity 21 // checks on the data. Set invalid values to zero. 22 public void SetTime( 23 int hourValue, int minuteValue, int secondValue ) 24 { 25 hour = ( hourValue >= 0 && hourValue < 24 ) ? 26 hourValue : 0; 27 minute = ( minuteValue >= 0 && minuteValue < 60 ) ? 28 minuteValue : 0; 29 second = ( secondValue >= 0 && secondValue < 60 ) ? 30 secondValue : 0; 31 } 32 Default constructorValidate arguments Time1 (subclass) inherits superclass System.Object (Chapter 11 discusses inheritance) private instance variables (and methods) are accessible only to methods in this class Time1 constructor creates Time1 object then invokes method setTime Method SetTime sets private variables according to arguments public methods (and variables) are accessible wherever program has Time1 reference  Note: If a class does not define Time1() the compiler will provide a default constructor and instance variables are initialized to 0, so the outputs without lines 15-18 is the same for the driver in Fig.10.2 Compare with the textbook ed. 5 p.373 line 24 throw new ArgumentOutOfRangeException() and p.375 line 28 – 35 – the try- catch block.

16  2002 Prentice Hall. All rights reserved. Outline 15 Time1.cs 33 // convert time to universal-time (24 hour) format string 34 public string ToUniversalString() 35 { 36 return String.Format( 37 "{0:D2}:{1:D2}:{2:D2}", hour, minute, second ); 38 } 39 40 // convert time to standard-time (12 hour) format string 41 public string ToStandardString() 42{ // D2 spec (a 2-digit base 10 decimal number format) 43 // causes single-digit values to appear 44 // as 2 digits with a leading 0 43 return String.Format( "{0}:{1:D2}:{2:D2} {3}", 44 ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ), 45 minute, second, ( hour < 12 ? "AM" : "PM" ) ); // a conditional operator 46 } 47 48 } // end class Time1 Output time in universal format Output time in standard format

17 Jozef Goetz, 2015 16 10.2Implementing a Time Abstract Data Type with a Class  Class definitions  Never really create definition from scratch –Use “ :” to inherit data and methods from base class Derived class: class that inherits  Every class in C# (or Java) is a subclass (derived class) of Object  Gets useful methods, discussed later  Every class in C# is a part of a namespace  If programmer doesn’t specify a namespace for a class, the default namespace is the current directory (where the project resides) which includes all compiled classes 7public class Time1 : Object {

18 Jozef Goetz, 2015 17 10.2Implementing a Time Abstract Data Type with a Class  Class body  Delineated by braces { }  Declare instance variables and methods  Classes simplify programming  Client only concerned with public operations  Client does not dependent on implementation details  Software reuse  can greatly enhance programmer productivity

19 Jozef Goetz, 2015 18 10.2Implementing a Time Abstract Data Type with a Class  Member-access modifiers  public : accessible whenever program has a reference to an object of the class  private : accessible only to member methods of that class  !!! Normally, member variables are usually private –using public data in a class is uncommon and dangerous programming practice  !! instance variables of a class are initialized in the class constructor 9 private int hour; // 0 - 23 10 private int minute; // 0 - 59 11 private int second; // 0 - 59

20 Jozef Goetz, 2015 19 10.2 Implementing a Time Abstract Data Type with a Class (cont.)  Every C# class must inherit another class  Time1 : System.Object  If class does not inherits another class  class implicitly inherits Object  Constructor 1.Special member method –Same name as the class 2.Initializes data members of a class object –Ensures objects start in consistent state – i.e. all instance variables have valid values (for ex. >= 0) 3.Constructors can be overloaded (more later) 4.Constructors cannot return values –No return type, not even void 15 public Time1()

21 Jozef Goetz, 2015 20 10.2Implementing a Time Abstract Data Type with a Class  Methods  Access methods –public methods that read/display data –public interface /public services –Clients use references to interact with objects via public methods Clients are users of a class. They manipulate the data stored in objects of the class  Utility methods –private methods that support access methods 22 public void setTime( int h, int m, int s ) 35 public String toUniversalString()

22  2002 Prentice Hall. All rights reserved. Outline 21 TimeTest1.cs 1 // Fig. 10.2: TimeTest1.cs 2 // Demonstrating class Time1. 3 4 using System; 5 using System.Windows.Forms; 6 7 // TimeTest1 uses creates and uses a Time1 object 8 class TimeTest1 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 Time1 time = new Time1(); // calls Time1 constructor 14 string output; 15 16 // assign string representation of time to output 17 output = "Initial universal time is: " + 18 time.ToUniversalString() + 19 "\nInitial standard time is: " + 20 time.ToStandardString(); 21 22 // attempt valid time settings 23 time.SetTime( 13, 27, 6 ); //the reference name specifies // the object that will receive the method call 24 25 // append new string representations of time to output 26 output += "\n\nUniversal time after SetTime is: " + 27 time.ToUniversalString() + 28 "\nStandard time after SetTime is: " + 29 time.ToStandardString(); 30 31 // attempt invalid time settings 32 time.SetTime( 99, 99, 99 ); // modify variables to be in // a consistent state 33 Call default time constructor Call method SetTime to set the time with valid arguments Call method SetTime with invalid arguments Compare with the textbook ed. 5 p.373 line 24 throw new ArgumentOutOfRangeException() and p.375 line 28 – 35 – the try- catch block.

23  2002 Prentice Hall. All rights reserved. Outline 22 34 output += "\n\nAfter attempting invalid settings: " + 35 "\nUniversal time: " + time.ToUniversalString() + 36 "\nStandard time: " + time.ToStandardString(); 37 38 MessageBox.Show( output, "Testing Class Time1" ); 39 40 } // end method Main 41 42 } // end class TimeTest1 Ed5: p.375 line 28-35: For values outside these ranges, SetTime throws an exception of type ArgumentOutOfRangeException, which notifies the client code that an invalid argument was passed to the method. throw new ArgumentOutOfRangeException() line 24 p.373 statement creates a new object of type ArgumentOutOfRangeException.

24 Jozef Goetz, 2015 23 10.2 Implementing a Time Abstract Data Type with a Class (cont.)  Information hiding promotes program modifiability and simplifies the client's perception of a class.  Clients of a class can (and should) use the class without knowing the internal details of how the class is implemented.  If the class implementation changes (to improve performance, for example), but the class interface remains constant, the client's source code need not change.  This makes it much easier to modify systems.  The use of an OOP approach often simplifies method calls by reducing the number of parameters that must be passed.  Because of the right to access the object's instance variables (class variables).

25 Jozef Goetz, 2015

26 25 Class Scope and this  Class scope  Instance variables and methods belong to that class’s scope  Class members accessible to methods  Can be referenced by name  Outside scope, cannot be referenced by name  Only visible are public members accessed through a handle objectReferenceName.variableName objectReferenceName.methodName()  Method scope  Variables defined in a method known only in that method  If variable has same name as class variable, class variable hidden  class variable hidden can be accessed using keyword this this.variableName (discussed later)

27 Jozef Goetz, 2015 26 10.3 Controlling Access to Members  Member access modifiers  Control access to class’ instance variables and methods  public  Variables and methods accessible to clients  Give clients a view of the services (operations) the class provides (interface)  private  Variables and methods not accessible to class clients  Data members should be declared private, with public methods that allow safe access to them –Accessor method (“ get ” method) Allow clients to read private data (property) –Mutator method (“ set ” method) - “translator” Translates between the format of the data in the interface and the format used in the implementation Allows clients to modify private data (property )  The client should not have access to helper methods, thus they should be declared private

28 Jozef Goetz, 2015 27 Outline  MemberAc cessTest.cs Attempting to access private instance variables

29 Jozef Goetz, 2015 28 10.4 Using the this reference  “ this ” reference  Allows an object to refers to itself  the object is initialized via InitializedComponent() methods  The “this” reference  Implicitly used to refer to the object’s instance variables, properties and methods  Inside methods:  “this” often used to distinguish between a method’s variables and the instance variables of an object  If parameter has same name as instance variable instance variable is hidden  Use this.variableName to explicitly refer to the instance variable  Use variableName to refer to the parameter of the method  “this” can increase program clarity

30 Jozef Goetz, 2015 29 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

31 Jozef Goetz, 2015 30 Outline  ThisTest.cs  (2 of 2) Using this explicitly and implicitly to call ToUniversalString Use of this not necessary here

32 Jozef Goetz, 2015 31 Initializing Class Objects: Constructors  Class constructor  Same name as class  Instances of classes are initialized by constructors  Initializes instance variables of a class object  Call class constructor to instantiate object of that class: ClassName objectRef = new ClassName (a rguments) ;  objectRef is a reference to appropriate data type (object)  new indicates that new object is created  ClassName indicates type of object created  arguments specifies constructor argument values  If no constructor defined, compiler makes default constructor:  all data members are initialized  Defaults: 0 for primitive numeric types, false for Boolean, null for references  Overloaded constructors may be used to provide different ways to initialize objects of a class  If a class has constructors, but not a default constructor, and a program attempts to call a no-argument constructor, a compilation error occurs.

33 Jozef Goetz, 2015 32 Performance Tip 10.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.

34 Jozef Goetz, 2015 33 10.5 Using Overloaded Constructors  Can initialize members of an object  No return type  Class may have overloaded constructors  Must have the same name  Must have different parameter lists (the number, types or order)  Initializers passes as arguments to constructor  Can have constructor with no arguments  C# invokes the appropriate constructor by matching –Types –Order –Number of parameters of the specified in the instructor call

35 Jozef Goetz, 2015 The parameterless constructor passes values (default are 0s) to the constructor with three int parameters. p.380 The use of the this reference as shown here is called a constructor initializer. Class Time2 with Overloaded Constructors Overloaded constructors enable objects of a class to be initialized in different ways. To overload constructors, simply provide multiple constructor declarations with different signatures. Class Time2 (Fig. 10.5) contains 2 overloaded constructors for conveniently initializing its objects in a variety of ways.

36 Jozef Goetz, 2015 In 3 rd edition 2008: 40 public int Hour 41 { 42 get 43 { 44 return hour; 45 } // end get 46 // make writing inaccessible outside the class 47 private set 48 { 49 hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); 50 } // end set 51 } // end property Hour

37 Jozef Goetz, 2015 In 3 rd edition 2008: 53 // property that gets and sets the minute 54 public int Minute 55 { 56 get 57 { 58 return minute; 59 } // end get 60 // make writing inaccessible outside the class 61 private set 62 { 63 minute = ( ( value >= 0 && value < 60 ) ? value : 0 ); 64 } // end set 65 } // end property Minute 75 private set 76 { 77 second = ( ( value >= 0 && value < 60 ) ? value : 0 ); 78 } // end set 79 } // end property Second

38 Jozef Goetz, 2015

39

40 <= catch <= try

41 Jozef Goetz, 2015 40 Properties  Public properties allow clients to:  Get (obtain the values of) private data  Set (assign values to) private data using “get” accessor and “set” accessor  we can use the property (e.g. public int Hour { } ) in the same way we use a variable (e.g. time.Hour)  the access is restricted by the class/method implementer  so it protects the instance variables from receiving invalid values  If implementation of a class changes  Clients can still use same methods as long the methods interface provided is preserved  Clients do not know implementation details

42 Jozef Goetz, 2015 41 Properties public string Name { get { return name; } set { name = value; } } “get” accessor : public “method” Allows clients to read/displays private data Again, does not violate notion of private data Can control display information and format “set” accessor : public “method” Allows clients to modify private data Does not violate notion of private data Can change only the data members (variables) and reject or correct data entered/received by the class implementer

43  2002 Prentice Hall. All rights reserved. Outline 42 Time3.cs 1 // Fig. 8.6 ed1 or 10.7 ed3: Time3.cs 2 // Class Time3 provides overloaded constructors. 3// and demonstrates properties Hour, Minute and Second 4 using System; 5 6 // Time3 class definition 7 public class Time3 8 { 9 private int hour; // 0-23 10 private int minute; // 0-59 11 private int second; // 0-59 12 13 // Time3 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time3() 16 { 17 SetTime( 0, 0, 0 ); 18 } 19 20 // Time3 constructor: hour supplied, minute and second 21 // defaulted to 0 22 public Time3( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 } 26 27 // Time3 constructor: hour and minute supplied, second 28 // defaulted to 0 29 public Time3( int hour, int minute ) 30 { 31 SetTime( hour, minute, 0 ); 32 } 33

44  2002 Prentice Hall. All rights reserved. Outline 43 34 // Time3 constructor: hour, minute and second supplied 35 public Time3( int hour, int minute, int second ) 36 { 37 SetTime( hour, minute, second ); 38 } 39 40 // Time3 constructor: initialize using another Time3 object 41 public Time3( Time3 time ) 42 { 43 SetTime( time.Hour, time.Minute, time.Second ); 44 } 45 46 // Set new time value in 24-hour format. Perform validity 47 // checks on the data. Set invalid values to zero. 48 public void SetTime( 49 int hourValue, int minuteValue, int secondValue ) 50 { 51 Hour = hourValue; // invoke corresponding property set 52 Minute = minuteValue; // invoke corresponding property set 53 Second = secondValue; // invoke corresponding property set 54 } 55 56 // property Hour 57 public int Hour // we can use the property in the same way we // use a variable 58 { 59 get // reserved word “get” 60 { 61 return hour; 62 } 63 64 set // reserved word “set” // value represents the argument to the set accessor 65 { 66 hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); 67 } 68 Constructor that takes another Time3 object as an argument. New Time3 object is initialized with the values of the argument. Property Hour or p.380

45  2002 Prentice Hall. All rights reserved. Outline 44 Time3.cs 69 } // end property Hour 70 71 // property Minute 72 public int Minute 73 { 74 get 75 { 76 return minute; 77 } 78 79 set 80 { 81 minute = ( ( value >= 0 && value < 60 ) ? value : 0 ); 82 } 83 84 } // end property Minute 85 86 // property Second 87 public int Second 88 { 89 get 90 { 91 return second; 92 } 93 94 set 95 { 96 second = ( ( value >= 0 && value < 60 ) ? value : 0 ); 97 } 98 99 } // end property Second 100 Property Minute Property Second

46  2002 Prentice Hall. All rights reserved. Outline 45 Time3.cs 101 // convert time to universal-time (24 hour) format string 102 public string ToUniversalString() 103 { 104 return String.Format( 105 "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second ); 106 } // use properties Hour, Minute, Second to obtain values of hour, minute, second 107 108 // convert time to standard-time (12 hour) format string 109 public string ToStandardString() 110 { 111 return String.Format( "{0}:{1:D2}:{2:D2} {3}", 112 ( ( Hour == 12 || Hour == 0 ) ? 12 : Hour % 12 ), 113 Minute, Second, ( Hour < 12 ? "AM" : "PM" ) ); 114 } 115 116 } // end class Time3

47  2002 Prentice Hall. All rights reserved. Outline 46 TimeTest3.cs 1 // Fig. 8.7 ed1: TimeTest3.cs 2 // Demonstrating Time3 properties Hour, Minute and Second. 3 // with enhanced GUI event-handling techniques 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // TimeTest3 class definition 12 public class TimeTest3 : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Label hourLabel; 15 private System.Windows.Forms.TextBox hourTextBox; 16 private System.Windows.Forms.Button hourButton; 17 18 private System.Windows.Forms.Label minuteLabel; 19 private System.Windows.Forms.TextBox minuteTextBox; 20 private System.Windows.Forms.Button minuteButton; 21 22 private System.Windows.Forms.Label secondLabel; 23 private System.Windows.Forms.TextBox secondTextBox; 24 private System.Windows.Forms.Button secondButton; 25 26 private System.Windows.Forms.Button addButton; 27 28 private System.Windows.Forms.Label displayLabel1; 29 private System.Windows.Forms.Label displayLabel2; 30 31 // required designer variable 32 private System.ComponentModel.Container components = null; 33

48  2002 Prentice Hall. All rights reserved. Outline 47 TimeTest3.cs 35 private Time3 time; 36 public TimeTest3() 37 { 38 // Required for Windows Form Designer support 39 InitializeComponent(); 40 41 time = new Time3(); // instantiate a Time3 object 42 UpdateDisplay(); 43 } 44 45 // Visual Studio.NET generated code 46 47 // main entry point for application 48 [STAThread] 49 static void Main() 50 { 51 Application.Run( new TimeTest3() ); 52 } 53 54 // update display labels 55 public void UpdateDisplay() 56 { 57 displayLabel1.Text = "Hour: " + time.Hour + 58 "; Minute: " + time.Minute + 59 "; Second: " + time.Second; 60 displayLabel2.Text = "Standard time: " + 61 time.ToStandardString() + "\nUniversal time: " + 62 time.ToUniversalString(); 63 } 64

49  2002 Prentice Hall. All rights reserved. Outline 48 TimeTest3.cs 65 // set Hour property when hourButton pressed 66 private void hourButton_Click( 67 object sender, System.EventArgs e ) 68 { 69 time.Hour = Int32.Parse( hourTextBox.Text ); 70 hourTextBox.Text = ""; 71 UpdateDisplay(); 72 } 73 74 // set Minute property when minuteButton pressed 75 private void minuteButton_Click( 76 object sender, System.EventArgs e ) 77 { 78 time.Minute = Int32.Parse( minuteTextBox.Text ); 79 minuteTextBox.Text = ""; 80 UpdateDisplay(); 81 } 82 83 // set Second property when secondButton pressed 84 private void secondButton_Click( 85 object sender, System.EventArgs e ) 86 { 87 time.Second = Int32.Parse( secondTextBox.Text ); 88 secondTextBox.Text = ""; 89 UpdateDisplay(); 90 } 91 92 // add one to Second when addButton pressed 93 private void addButton_Click( 94 object sender, System.EventArgs e ) 95 { 96 time.Second = ( time.Second + 1 ) % 60; 97 Set Hour property of Time3 object Set Minute property of Time3 object Set Second property of Time3 object Add 1 second to Time3 object

50  2002 Prentice Hall. All rights reserved. Outline 49 TimeTest3.cs Program Output 98 if ( time.Second == 0 ) 99 { 100 time.Minute = ( time.Minute + 1 ) % 60; 101 102 if ( time.Minute == 0 ) 103 time.Hour = ( time.Hour + 1 ) % 24; 104 } 105 106 UpdateDisplay(); 107 } 108 109 } // end class TimeTest3

51 Jozef Goetz, 2015 50 Software Engineering Observations  Accessing private data through set and get accessors  protects the instance variables from receiving invalid values, but  also hides the internal representation of the instance variables from that class's clients.  if representation of the data changes (typically, to reduce the amount of required storage or to improve performance), only the method implementations need to change  the client implementations don’t need to be changed, as long as the interface provided by the methods is preserved.

52 Jozef Goetz, 2015 51 10.7 Composition: Object References as Instance Variables of Other Classes  Composition  Class contains references to objects of other classes  These references are members  Not required to be immediately initialized –Default constructor automatically called  Software Reuse – referencing existing object is easier and faster than rewriting the objects’ code for new classes  Use user-defined types as instance variables  Upcoming example  Class Date  Instance variables month, day, year  Class Employee  Instance variables firstName, lastName  Composition: has Date references birthDate, hireDate

53 Jozef Goetz, 2015 52 Date.cs (1, 2 of 4 ) Fig. 10.7 | Date class declaration. (Part 1, 2 of 4.) Output: Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949 Class Date (Fig. 10.7) declares instance variables month and day, and auto- implemented property Year (line 11) to represent a date.

54 Jozef Goetz, 2015 53 Fig. 10.7 | Date class declaration. (Part 3 of 4.) else { Console.WriteLine( "Invalid month ({0}) set to 1.", value ); month = 1; } // maintain object in consistent state

55 Jozef Goetz, 2015 54 Outline Date.cs (4 of 4 ) Fig. 10.7 | Date class declaration. (Part 4 of 4.) Output: Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949 else { Console.WriteLine( "Invalid day ({0}) set to 1.", value ); 63 day = 1; // maintain object in consistent state 64 } // end else

56 Jozef Goetz, 2015 55 Class Employee (Fig. 10.8) has instance variables firstName, lastName, birthDate and hireDate. Outline Employee.cs (1 of 2 ) Fig. 10.8 | Employee class with references to other objects. (Part 1 of 2.) Members birthDate and hireDate are references to Date objects, demonstrating that a class can have as instance variables references to objects of other classes.

57 Jozef Goetz, 2015 56 Outline Employee.cs (2 of 2 ) Fig. 10.8 | Employee class with references to other objects. (Part 2 of 2.) Output: Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949

58 Jozef Goetz, 2015 57 Class Employee­Test (Fig. 10.9) creates two Date objects to represent an Employee ’s birthday and hire date, respectively. Outline EmployeeTest.cs Fig. 10.9 | Composition demonstration. Pass the names and two Date objects to the Employee constructor.

59 Jozef Goetz, 2015 58 10.8 Garbage Collection  Operator new allocates memory  When objects are no longer referenced, the CLR (Common Language Runtime) performs garbage collection  It locates objects with no references  Garbage collection helps avoid memory leaks (i.e. running out of memory because unused memory has not been reclaimed)  Memory leaks are in C and C++ applications but are rare in C# and Java  But allocation and deallocation of other resources  file access,  database connections,  network connections etc.  must be explicitly handled by programmers

60 Jozef Goetz, 2015 59 10.8 Garbage Collection  Use finalizers (destructors) in conjunction with the garbage collector to release resources and memory  Performs termination housekeeping on object  Before garbage collector reclaims an object’s memory, it calls the object’s finalizer  we cannot determine exactly when garbage collection occurs except  OS recovers the memory when the program terminates  Each class has only one finalizer (also called destructor)  Name of a destructor is the ~ character, followed by the class name  Destructors do not receive any arguments  so they cannot be overloaded

61 Jozef Goetz, 2015 60 10.9 Static Class Members  Available as soon as the class is loaded into memory at execution time and  they exists for the duration of a program execution, even when no objects of that class exists  Every object of a class has its own copy of all instance variables  Sometimes it is useful if all instances (objects) of a class share the same copy of a variable  Declare variables using keyword static to create only one copy of the variable at a time (shared by all objects of the type)  Static variable have class scope (global to the class)  Can be public, private, etc.

62 Jozef Goetz, 2015 61 10.9 static Class Members  Static variables  public static data members  Accessed through references or class name and dot operator –MyClass.myStaticVariable –Math.PI  private static data members  Accessed only through methods or properties of the class  If no objects exist, the class must provide a public static method or property –MyClass.MyMethod()

63 Jozef Goetz, 2015 62 10.9 static Class Members  Static methods  Can only access static members because are independent of objects  A static method cannot access non-static members.  Have no “ this” reference  static variables independent of objects  Method System.GC.Collect()  public static method of class System –System.GC.Collect()  Suggests garbage collector execute immediately –Can be ignored –Garbage collector not guaranteed to collect objects in a specific order

64 Jozef Goetz, 2015 63 10.9 static Class Members  Upcoming example  Class Employee  private static variable count (number of Employee objects)  public static property Count - returns count  Class StaticTest  Create Employee objects  Call getCount

65 Jozef Goetz, 2015 64 Outline Employee.cs (1 of 2 ) Class Employee (Fig. 10.10) declares private static variable count and public static property Count. Fig. 10.12 | static variable used to maintain a count of the number of Employee objects in memory. (Part 1 of 2.) If a static variable is not initialized, the compiler assigns a default value to the variable.

66 Jozef Goetz, 2015 65 Outline Employee.cs (2 of 2 ) Fig. 10.12 | static variable used to maintain a count of the number of Employee objects in memory. (Part 2 of 2.) Variable count maintains a count of the number of objects of class Employee that have been created. When no objects of class Employee exist, member count can only be referenced through a call to public static property Count. If a static variable is not initialized, the compiler assigns a default value to the variable. Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1 Employee constructor: Bob Blue; count = 2 Employees after instantiation: 2 Employee 1: Susan Baker Employee 2: Bob Blue

67 Jozef Goetz, 2015 66 Outline EmployeeTest.cs (1 of 2 ) EmployeeTest method Main (Fig. 10.11) instantiates two Employee objects. Fig. 10.13 | static member demonstration. (Part 1 of 2.) Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1 Employee constructor: Bob Blue; count = 2 Employees after instantiation: 2 Employee 1: Susan Baker Employee 2: Bob Blue

68 Jozef Goetz, 2015 67 Outline EmployeeTest.cs (2 of 2 ) Fig. 10.13 | static member demonstration. (Part 2 of 2.) After objects’ destructors are called, the objects become “eligible for garbage collection”. Eventually, the garbage collector reclaim the memory for these objects”

69  2002 Prentice Hall. All rights reserved. Outline 68 1 // Fig. 9.12: ed2 Employee.cs 2 // Employee class demonstrates static data and a static property. 3 4 using System; 5 6 // Employee class definition 7 public class Employee 8 { 9 private string firstName; 10 private string lastName; 11 private static int count; // # of employees objects in memory // initializes to 0 by default 13 // constructor increments static Employee count 14 public Employee( string fName, string lName ) 15 { 16 firstName = fName; 17 lastName = lName; 18 19 ++count; 20 21 Console.WriteLine( "Employee object constructor: " + 22 firstName + " " + lastName + "; count = " + Count ); 23 } 24 25 // destructor decrements static Employee count 26 // destructor role is to release resources and memory 27 // - performs termination housekeeping on object 26 ~Employee() 27 { 28 --count; 29 30 Console.WriteLine( "Employee object destructor: " + 31 firstName + " " + lastName + "; count = " + Count ); 32 } 33 Employee destructor Decrease static member count, to signify that there is one less employee Update number of Employees Employees before instantiation: 0 Employee object constructor: Susan Baker; count = 1 Employee object constructor: Bob Jones; count = 2 Employees after instantiation: Employee.Count = 2 Employee 1: Susan Baker Employee 2: Bob Jones Employee object destructor: Bob Jones; count = 1 Employee object destructor: Susan Baker; count = 0 Employees after garbage collection: 0 Note: it happened that the destructor is called in a different order

70  2002 Prentice Hall. All rights reserved. Outline 69 Employee.cs 34 // FirstName property 35 public string FirstName 36 { 37 get 38 { 39 return firstName; 40 } 41 } 42 43 // LastName property 44 public string LastName 45 { 46 get 47 { 48 return lastName; 49 } 50 } 51 52 // static Count property 53 public static int Count 54 { 55 get 56 { 57 return count; // can access only static members 58 } 59 } 60 61 } // end class Employee

71  2002 Prentice Hall. All rights reserved. Outline 70 1 // Fig. 9.13: ed2 StaticTest.cs 2 // Demonstrating static class members. 3 4 using System; 5 6 // StaticTest class definition 7 class StaticTest 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 Console.WriteLine( "Employees before instantiation: " + 13 Employee.Count + "\n" ); 14 15 // create two Employees 16 Employee employee1 = new Employee( "Susan", "Baker" ); 17 Employee employee2 = new Employee( "Bob", "Jones" ); 18 19 Console.WriteLine( "\nEmployees after instantiation: " + 20 "Employee.Count = " + Employee.Count + "\n" ); 21 22 // display the Employees 23 Console.WriteLine( "Employee 1: " + 24 employee1.FirstName + " " + employee1.LastName + 25 "\nEmployee 2: " + employee2.FirstName + 26 " " + employee2.LastName + "\n" ); 27 28 // mark employee1 and employee1 objects for 29 // garbage collection 30 employee1 = null; 31 employee2 = null; 32 33 // force garbage collection; // it is not guaranteed to collect objects in a specific order 34 System.GC.Collect(); // class GC executes a thread 35 // the output (the order of reclaiming memory) could be // different Create 2 Employee objects Set Employee objects to null Force garbage collection Employees before instantiation: 0 Employee object constructor: Susan Baker; count = 1 Employee object constructor: Bob Jones; count = 2 Employees after instantiation: Employee.Count = 2 Employee 1: Susan Baker Employee 2: Bob Jones Employee object destructor: Bob Jones; count = 1 Employee object destructor: Susan Baker; count = 0 Employees after garbage collection: 0

72  2002 Prentice Hall. All rights reserved. Outline 71 StaticTest.cs Program Output 36 // wait until garbage collector invokes the destructors for // all objects completes, so count has been decremented accordingly System.GC.WaitForPendingFinalizers(); Console.WriteLine( 37 "\nEmployees after garbage collection: " + 38 Employee.Count ); 39 } 40 } Employees before instantiation: 0 Employee object constructor: Susan Baker; count = 1 Employee object constructor: Bob Jones; count = 2 Employees after instantiation: Employee.Count = 2 Employee 1: Susan Baker Employee 2: Bob Jones Employee object destructor: Bob Jones; count = 1 Employee object destructor: Susan Baker; count = 0 Employees after garbage collection: 0

73 Jozef Goetz, 2015 72 10.10 const Members  Declare constant members (members whose value will never change) using the keyword const  const members are implicitly static  const members must be initialized when they are declared  variable is not modifiable,  must be initialized in its declaration  initialized at compile time  e.g. public const double PI = 3.14159;

74 Jozef Goetz, 2015 73 10.10 readonly Members  Use keyword readonly (no in Java) to declare members who must be initialized at execution time in a constructor  if members are not initialized in their declaration  Must be assigned in every constructor of the class  But only one of which will be called when an object is initialized  When a static readonly member is initialized in a constructor, a static constructor must be used.

75  2002 Prentice Hall. All rights reserved. Outline 74 UsingConstAndRea dOnly.cs 1 // Fig. 8.15 ed1 (see 10.14 in new ed3 ) : UsingConstAndReadOnly.cs 2 // Demonstrating constant values with const and readonly. 3 4 using System; 5 using System.Windows.Forms; 6 7 // Constants class definition 8 public class Constants 9 { 10 // PI is constant variable 11 public const double PI = 3.14159; // initialized at compile time 12 // const is treated as staic 12 13 // radius is a constant variable 14 // that is uninitialized; initialized at execution time: 15 public readonly int radius; // when program creates Constants obj 16 17 public Constants( int radiusValue ) 18 { 19 radius = radiusValue; 20 } 21 22 } // end class Constants 23 24 // UsingConstAndReadOnly class definition 25 public class UsingConstAndReadOnly 26 { 27 // method Main creates Constants 28 // object and displays it's values 29 static void Main( string[] args ) 30 { 31 Random random = new Random(); 32 33 Constants constantValues = 34 new Constants( random.Next( 1, 20 ) ); //passed a radius 35 Constant variable PI Readonly variable radius; must be initialized in constructor Initialize readonly member radius

76  2002 Prentice Hall. All rights reserved. Outline 75 UsingConstAndRea dOnly.cs Program Output 36 MessageBox.Show( "Radius = " + constantValues.radius + 37 "\nCircumference = " + 38 2 * Constants.PI * constantValues.radius, 39 "Circumference" ); // use static syntax to access PI 40 // Constants.PI 41 } // end method Main 42 43 } // end class UsingConstAndReadOnly

77 Jozef Goetz, 2015 76 10.11 Data Abstraction and Information Hiding  VB.NET and C#  Focus on creating new data type (classes)  Abstract Data Types (ADTs)  Ways to represent real-world notions  Imperfect –Single and Double have finite precision –Integer has a maximum size  In reality (in math), there is infinite precision and no maximum size  Captures two notions  Data representation  Operations  Use classes to implement them  Extend the base programming language

78 Jozef Goetz, 2015 77 10.11 Data Abstraction and Information Hiding  Encapsulation (data hiding by declaring private variables)  Classes hide implementation details from clients  Example of ADT: stack data structure  Last-in, first out (LIFO)  e.g. Cafeteria trays that are put on top of each other  Data elements like a pile of dishes – –added (pushed) and –removed (popped) from top  Developer creates stack –Hides stack’s implementation details from clients  In Abstract data types (ADTs)  Client does not care how stack is implemented –Wants to know what functionality a class (here stack) offers by specification of the public services (public methods)

79 Jozef Goetz, 2015 78 10.11 Data Abstraction and Information Hiding  Classes should hide implementation details  Example: queue - a waiting line  Line at grocery store  First-in, first-out (FIFO)  e.g. Printing machine that prints documents in FIFO order –Enqueue to add objects in queue –Dequeue to remove object from queue  Enqueue and dequeue hide internal data representation  Implementation hidden from clients  Only queue member functions can access internal data

80 Jozef Goetz, 2015 79 Software Reusability  The Framework Class Library (FCL) contains thousands of predefined classes  The FCL classes should be used whenever possible  No bugs  Optimized  Well-documented  Reusing code facilitates Rapid Application Development (RAD)  Software reusability speeds the development of powerful, high quality software. The Framework Class Library (FCL) includes classes for creating Web Services  Which are applications packaged as services that client can access via the Internet  Any C# application is a potential Web service, so C# programmers can reuse existing applications as building blocks to form larger more sophisticated Web-enabled applications.

81 Jozef Goetz, 2015 80 Namespaces and Assemblies  Problem: If 2 programmers used the same class names and if the program needs both of those classes the program must have a way to distinguish between 2 classes in the code  Namespaces provides a convention for unique class names  Namespaces provide logical grouping of classes  No two classes in the same namespace may have the same name  Classes in different namespaces may have the same name  Software components should be reusable  Dynamic Link Libraries – DLL (.dll files) allow classes to be packaged for reuse

82 Jozef Goetz, 2015 81 Namespaces and Assemblies  A DLL represents an assembly.  When a project uses a class library,  it must contain a reference to the assembly that defines the class library .dll can be loaded dynamically by other appls and shared among those appls  Only public classes can be reused from class library.  Non-public classes can be used only by other classes in the same assembly

83 Jozef Goetz, 2015 82 Time Class Case Study: Creating Class Libraries  Steps for Declaring and Using a Reusable Class 1.Declare a public class 2.Choose a namespace name and add a namespace declaration to the source-code file for the reusable class 3.Compile the class into a class library.dll 4.Add a reference to the class library in an application 5.Specify a using directive for the namespace of the reusable class

84 Jozef Goetz, 2015 83 Outline  Time1.cs

85 Jozef Goetz, 2015 84 | Creating a Class Library Project. | Adding a Reference.

86 Jozef Goetz, 2015 85 Outline  Time1NamespaceTest.cs

87 Jozef Goetz, 2015 86 internal Access  Classes can be declared with only 2 access modifiers  public  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

88 Jozef Goetz, 2015 87 Outline  InternalAccessTest.cs  (1 of 2) After instantiation: number: 0; message: Hello After changing values: number: 77; message: Goodbye

89 Jozef Goetz, 2015 88 Outline  InternalAccessTe st.cs  (2 of 2)

90 Jozef Goetz, 2015 89 10.12 Class View and Object Browser  Class View and Object Browser are features of Visual Studio that facilitate the design of object- oriented applications  Class View  Displays variables and methods for all classes in a project  Displays as treeview hierarchical structure  + at nodes allows nodes to be expanded  - at nodes allows nodes to be collapsed  Can be seen by selecting View => Class View Fig. 10.12 Class View of class Time1 and class TimeTest

91 Jozef Goetz, 2015 90 10.12 Class View and Object Browser Fig. Object Browser when user selects Object from Time1.cs.  Object Browser  Lists all classes in a library  Helps developers learn about the functionality of a specific class  To view the Object Browser select any.NET FCL method in the code editor and select Go To Definition

92 Jozef Goetz, 2015 91 Fig. 10.13 | Object Browser for class Math.

93 Jozef Goetz, 2015 92 Outline Time.cs (1 of 4 ) Visual C# 2008/2010 provides a new feature—object initializers—that allow you to create an object and initialize its properties in the same statement. Object initializers are useful when a class does not provide an appropriate constructor to meet your needs. For this example, we created a version of the Time class (Fig. 10.23 ed3) in which we did not define any constructors. Fig. 10.23 | Time class declaration maintains the time in 24-hour format. (Part 1 of 4.) 10.13 Object Initializers

94 Jozef Goetz, 2015 93 Outline Time.cs (2 of 4 ) Fig. 10.23 | Time class declaration maintains the time in 24-hour format. (Part 2 of 4.)

95 Jozef Goetz, 2015 94 Outline Time.cs (3 of 4 ) Fig. 10.23 | Time class declaration maintains the time in 24-hour format. (Part 3 of 4.)

96 Jozef Goetz, 2015 95 Outline Time.cs (4 of 4 ) Fig. 10.23 | Time class declaration maintains the time in 24-hour format. (Part 4 of 4.)

97 Jozef Goetz, 2015 96 Outline ObjectInitializer Test.cs (1 of 2 ) Figure 10.24 ed3 demonstrates object initializers. Fig. 10.24 | Demonstrate object initializers using class Time. (Part 1 of 2.) The class name is immediately followed by an object-initializer list - a comma-separated list in curly braces ( { } ) of properties and their values. Time object created with object initializer Standard time: 2:00:12 PM Universal time: 14:00:12 Time object created with Minute property set Standard time: 12:45:00 AM Universal time: 00:45:00

98 Jozef Goetz, 2015 97 Outline ObjectInitializer Test.cs (2 of 2 ) Fig. 10.24 | Demonstrate object initializers using class Time. (Part 2 of 2.)

99 Jozef Goetz, 2015 98 10.17 Object Initializers (Cont.) The class name is immediately followed by an object-initializer list—a comma-separated list in curly braces ({ }) of properties and their values. Each property name can appear only once in the object-initializer list. The object-initializer list cannot be empty. The object initializer executes the property initializers in the order in which they appear. An object initializer first calls the class’s constructor, so any values not specified in the object initializer list are given their values by the constructor.


Download ppt "Jozef Goetz, 2015 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. ©1992-2014 by Pearson Education, Inc."

Similar presentations


Ads by Google