Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 – Object-Based Programming

Similar presentations


Presentation on theme: "Chapter 8 – Object-Based Programming"— Presentation transcript:

1 Chapter 8 – Object-Based Programming
Outline Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Initializing Class Objects: Constructors Using Overloaded Constructors Properties Composition: Objects as Instance Variables of Other Classes Using the this Reference Garbage Collection static Class Members const and readonly Members Indexers Data Abstraction and Information Hiding Software Reusability Namespaces and Assemblies Class View and Object Browser

2 Object classes encapsulate (wrap together) data and methods
8.1 Introduction Object classes encapsulate (wrap together) data and methods Objects can hide implementation from other objects (information hiding) Methods : units of programming User-defined type: class written by a programmer Classes have Data members (member variable or instance variables) Methods that manipulate the data members

3 8.2 Implementing a Time Abstract Data Type with a Class
Abstract Data Types – hide implementation from other objects The opening left brace ({) and closing right brace (}) delimit the body of a class Variables inside the class definition but not a method definition are called instance variables Member Access Modifiers public : member is accessible wherever an instance of the object exists private : members is accessible only inside the class definition

4 8.2 Implementing a Time Abstract Data Type with a Class
Access methods : read or display data Predicate methods : test the truth of conditions Constructor Initializes objects of the class Can take arguments Cannot return values There may be more then one constructor per class (overloaded constructors) Operator new used to instantiate classes Use Project < Add Class to add a new class to your project

5 Private instance variables Time1.cs
1 // Fig. 8.1: Time1.cs 2 // Class Time1 maintains time in 24-hour format. 3 4 using System; 5 6 // Time1 class definition 7 public class Time1 : Object 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // Time1 constructor initializes instance variables to // zero to set default time to midnight public Time1() { SetTime( 0, 0, 0 ); } 19 // Set new time value in 24-hour format. Perform validity // checks on the data. Set invalid values to zero. public void SetTime( int hourValue, int minuteValue, int secondValue ) { hour = ( hourValue >= 0 && hourValue < 24 ) ? hourValue : 0; minute = ( minuteValue >= 0 && minuteValue < 60 ) ? minuteValue : 0; second = ( secondValue >= 0 && secondValue < 60 ) ? secondValue : 0; } 32 Default constructor Private instance variables Time1.cs Method SetTime Validate arguments

6 Output time in universal format Time1.cs
// convert time to universal-time (24 hour) format string public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second ); } 39 // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } 47 48 } // end class Time1 Output time in universal format Time1.cs Output time in standard format

7 Call default time constructor
1 // Fig. 8.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 { // main entry point for application static void Main( string[] args ) { Time1 time = new Time1(); // calls Time1 constructor string output; 15 // assign string representation of time to output output = "Initial universal time is: " + time.ToUniversalString() + "\nInitial standard time is: " + time.ToStandardString(); 21 // attempt valid time settings time.SetTime( 13, 27, 6 ); 24 // append new string representations of time to output output += "\n\nUniversal time after SetTime is: " + time.ToUniversalString() + "\nStandard time after SetTime is: " + time.ToStandardString(); 30 // attempt invalid time settings time.SetTime( 99, 99, 99 ); 33 Call default time constructor TimeTest1.cs Call method SetTime to set the time with valid arguments Call method SetTime with invalid arguments

8 TimeTest1.cs Program Output
output += "\n\nAfter attempting invalid settings: " + "\nUniversal time: " + time.ToUniversalString() + "\nStandard time: " + time.ToStandardString(); 37 MessageBox.Show( output, "Testing Class Time1" ); 39 } // end method Main 41 42 } // end class TimeTest1 TimeTest1.cs Program Output

9 Method-scope variables
8.3 Class Scope All members are accessible within the class’s methods and can be referenced by name Outside a class, members cannot be referenced by name, public members may be referenced using the dot operator (referenceName.memberName ) Method-scope variables Only accessible within the methods in which they are defined Hide instance variables Instance variables may be accessed by using the keyword this and the dot operator (such as this.hour).

10 8.4 Controlling Access to Members
Public methods present to the class’s clients a view of the services that the class provides 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 Properties should be used to provide access to data safely (Section 8.7) Data members should be declared private, with public properties that allow safe access to them Properties get accessor : enables clients to read data set access : enables clients to modify data

11 RestrictedAccess.cs Program Output
1 // Fig. 8.3: RestrictedAccess.cs 2 // Demonstrate compiler errors from attempt to access 3 // private class members. 4 5 class RestrictedAccess 6 { // main entry point for application static void Main( string[] args ) { Time1 time = new Time1(); 11 time.hour = 7; time.minute = 15; time.second = 30; } 16 17 } // end class RestrictedAccess Attempt to access private members RestrictedAccess.cs Program Output

12 8.5 Initializing Class Objects: Constructors
Instances of classes are initialized by constructors Constructors initialize the instance variables of objects Overloaded constructors may be used to provide different ways to initialize objects of a class Even if the constructor does not explicitly do so, all data members are initialized Primitive numeric types are set to 0 Boolean types are set to false Reference types are set to null If a class has no constructor, a default constructor is provided It has no code and takes no parameters

13 Constructor which takes the hour as the input
1 // Fig. 8.4: Time2.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time2 class definition 7 public class Time2 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // Time2 constructor initializes instance variables to // zero to set default time to midnight public Time2() { SetTime( 0, 0, 0 ); } 19 // Time2 constructor: hour supplied, minute and second // defaulted to 0 public Time2( int hour ) { SetTime( hour, 0, 0 ); } 26 // Time2 constructor: hour and minute supplied, second // defaulted to 0 public Time2( int hour, int minute ) { SetTime( hour, minute, 0 ); } 33 Default constructor Time2.cs Constructor which takes the hour as the input Constructor which takes the hour and minute as input

14 Time2.cs 66 // convert time to standard-time (12 hour) format string
public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } 73 74 } // end class Time2 Time2.cs

15 TimeTest2.cs Test the constructors 1 // Fig. 8.5: TimeTest2.cs
2 // Using overloaded constructors. 3 4 using System; 5 using System.Windows.Forms; 6 7 // TimeTest2 demonstrates constructors of class Time2 8 class TimeTest2 9 { // main entry point for application static void Main( string[] args ) { Time2 time1, time2, time3, time4, time5, time6; 14 time1 = new Time2(); // 00:00:00 time2 = new Time2( 2 ); // 02:00:00 time3 = new Time2( 21, 34 ); // 21:34:00 time4 = new Time2( 12, 25, 42 ); // 12:25:42 time5 = new Time2( 27, 74, 99 ); // 00:00:00 time6 = new Time2( time4 ); // 12:25:42 21 String output = "Constructed with: " + "\ntime1: all arguments defaulted" + "\n\t" + time1.ToUniversalString() + "\n\t" + time1.ToStandardString(); 26 output += "\ntime2: hour specified; minute and " + "second defaulted" + "\n\t" + time2.ToUniversalString() + "\n\t" + time2.ToStandardString(); 31 output += "\ntime3: hour and minute specified; " + "second defaulted" + "\n\t" + time3.ToUniversalString() + "\n\t" + time3.ToStandardString(); TimeTest2.cs Test the constructors

16 TimeTest2.cs Program Output
36 output += "\ntime4: hour, minute, and second specified" + "\n\t" + time4.ToUniversalString() + "\n\t" + time4.ToStandardString(); 40 output += "\ntime5: all invalid values specified" + "\n\t" + time5.ToUniversalString() + "\n\t" + time5.ToStandardString(); 44 output += "\ntime6: Time2 object time4 specified" + "\n\t" + time6.ToUniversalString() + "\n\t" + time6.ToStandardString(); 48 MessageBox.Show( output, "Demonstrating Overloaded Constructors" ); 51 } // end method Main 53 54 } // end class TimeTest2 TimeTest2.cs Program Output

17 Public properties allow clients to:
Get (obtain the values of) private data Set (assign values to) private data Get accessor Controls formatting of data Set accessor Ensure that the new value is appropriate for the data member

18 1 // Fig. 8.6: Time3.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time3 class definition 7 public class Time3 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // Time3 constructor initializes instance variables to // zero to set default time to midnight public Time3() { SetTime( 0, 0, 0 ); } 19 // Time3 constructor: hour supplied, minute and second // defaulted to 0 public Time3( int hour ) { SetTime( hour, 0, 0 ); } 26 // Time3 constructor: hour and minute supplied, second // defaulted to 0 public Time3( int hour, int minute ) { SetTime( hour, minute, 0 ); } 33 Time3.cs

19 34 // Time3 constructor: hour, minute and second supplied
public Time3( int hour, int minute, int second ) { SetTime( hour, minute, second ); } 39 // Time3 constructor: initialize using another Time3 object public Time3( Time3 time ) { SetTime( time.Hour, time.Minute, time.Second ); } 45 // Set new time value in 24-hour format. Perform validity // checks on the data. Set invalid values to zero. public void SetTime( int hourValue, int minuteValue, int secondValue ) { Hour = hourValue; Minute = minuteValue; Second = secondValue; } 55 // property Hour public int Hour { get { return hour; } 63 set { hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); } 68 Constructor that takes another Time3 object as an argument. New Time3 object is initialized with the values of the argument. Time3.cs Property Hour

20 Property Second Time3.cs Property Minute 69 } // end property Hour 70
public int Minute { get { return minute; } 78 set { minute = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 83 } // end property Minute 85 // property Second public int Second { get { return second; } 93 set { second = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 98 } // end property Second 100 Property Second Time3.cs Property Minute

21 Time3.cs 101 // convert time to universal-time (24 hour) format string
public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second ); } 107 // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( Hour == 12 || Hour == 0 ) ? 12 : Hour % 12 ), Minute, Second, ( Hour < 12 ? "AM" : "PM" ) ); } 115 116 } // end class Time3 Time3.cs

22 TimeTest3.cs 1 // Fig. 8.7: TimeTest3.cs
2 // Demonstrating Time3 properties Hour, Minute and Second. 3 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 { private System.Windows.Forms.Label hourLabel; private System.Windows.Forms.TextBox hourTextBox; private System.Windows.Forms.Button hourButton; 17 private System.Windows.Forms.Label minuteLabel; private System.Windows.Forms.TextBox minuteTextBox; private System.Windows.Forms.Button minuteButton; 21 private System.Windows.Forms.Label secondLabel; private System.Windows.Forms.TextBox secondTextBox; private System.Windows.Forms.Button secondButton; 25 private System.Windows.Forms.Button addButton; 27 private System.Windows.Forms.Label displayLabel1; private System.Windows.Forms.Label displayLabel2; 30 // required designer variable private System.ComponentModel.Container components = null; 33 private Time3 time; 35 TimeTest3.cs

23 TimeTest3.cs 36 public TimeTest3() 37 {
{ // Required for Windows Form Designer support InitializeComponent(); 40 time = new Time3(); UpdateDisplay(); } 44 // Visual Studio .NET generated code 46 // main entry point for application [STAThread] static void Main() { Application.Run( new TimeTest3() ); } 53 // update display labels public void UpdateDisplay() { displayLabel1.Text = "Hour: " + time.Hour + "; Minute: " + time.Minute + "; Second: " + time.Second; displayLabel2.Text = "Standard time: " + time.ToStandardString() + "\nUniversal time: " + time.ToUniversalString(); } 64 TimeTest3.cs

24 Set Minute property of Time3 object
// set Hour property when hourButton pressed private void hourButton_Click( object sender, System.EventArgs e ) { time.Hour = Int32.Parse( hourTextBox.Text ); hourTextBox.Text = ""; UpdateDisplay(); } 73 // set Minute property when minuteButton pressed private void minuteButton_Click( object sender, System.EventArgs e ) { time.Minute = Int32.Parse( minuteTextBox.Text ); minuteTextBox.Text = ""; UpdateDisplay(); } 82 // set Second property when secondButton pressed private void secondButton_Click( object sender, System.EventArgs e ) { time.Second = Int32.Parse( secondTextBox.Text ); secondTextBox.Text = ""; UpdateDisplay(); } 91 // add one to Second when addButton pressed private void addButton_Click( object sender, System.EventArgs e ) { time.Second = ( time.Second + 1 ) % 60; 97 Set Minute property of Time3 object Set Hour property of Time3 object TimeTest3.cs Set Second property of Time3 object Add 1 second to Time3 object

25 TimeTest3.cs Program Output
if ( time.Second == 0 ) { time.Minute = ( time.Minute + 1 ) % 60; 101 if ( time.Minute == 0 ) time.Hour = ( time.Hour + 1 ) % 24; } 105 UpdateDisplay(); } 108 109 } // end class TimeTest3 TimeTest3.cs Program Output

26 TimeTest3.cs Program Output

27 TimeTest3.cs Program Output

28 8.8 Composition: Object References as Instance Variables of Other Classes
Software Reuse – referencing existing object is easier and faster then rewriting the objects’ code for new classes Use user-defined types as instance variables

29 1 // Fig. 8.8: Date.cs 2 // Date class definition encapsulates month, day and year. 3 4 using System; 5 6 // Date class definition 7 public class Date 8 { private int month; // 1-12 private int day; // 1-31 based on month private int year; // any year 12 // constructor confirms proper value for month; // call method CheckDay to confirm proper // value for day public Date( int theMonth, int theDay, int theYear ) { // validate month if ( theMonth > 0 && theMonth <= 12 ) month = theMonth; 21 else { month = 1; Console.WriteLine( "Month {0} invalid. Set to month 1.", theMonth ); } 28 year = theYear; // could validate year day = CheckDay( theDay ); // validate day } 32 Constructor that receives the month, day and year arguments. Arguments are validated; if they are not valid, the corresponding member is set to a default value Date.cs

30 Validate that the given month can have a given day number Date.cs
// utility method confirms proper day value // based on month and year private int CheckDay( int testDay ) { int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 39 // check if day in range for month if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) return testDay; 43 // check for leap year if ( month == 2 && testDay == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) return testDay; 49 Console.WriteLine( "Day {0} invalid. Set to day 1.", testDay ); 52 return 1; // leave object in consistent state } 55 // return date string as month/day/year public string ToDateString() { return month + "/" + day + "/" + year; } 61 62 } // end class Date Validate that the given month can have a given day number Date.cs

31 Two Date objects are members of the Employee class
1 // Fig. 8.9: Employee.cs 2 // Employee class definition encapsulates employee's first name, 3 // last name, birth date and hire date. 4 5 using System; 6 7 // Employee class definition 8 public class Employee 9 { private string firstName; private string lastName; private Date birthDate; private Date hireDate; 14 // constructor initializes name, birth date and hire date public Employee( string first, string last, int birthMonth, int birthDay, int birthYear, int hireMonth, int hireDay, int hireYear ) { firstName = first; lastName = last; 22 // create new Date for Employee birth day birthDate = new Date( birthMonth, birthDay, birthYear ); hireDate = new Date( hireMonth, hireDay, hireYear ); } 27 Two Date objects are members of the Employee class Employee.cs Constructor that initializes the employee’s name, birth date and hire date

32 Employee.cs 28 // convert Employee to String format
public string ToEmployeeString() { return lastName + ", " + firstName + " Hired: " + hireDate.ToDateString() + " Birthday: " + birthDate.ToDateString(); } 35 36 } // end class Employee Employee.cs

33 CompositionTest.cs Program Output
1 // Fig. 8.10: CompositionTest.cs 2 // Demonstrate an object with member object reference. 3 4 using System; 5 using System.Windows.Forms; 6 7 // Composition class definition 8 class CompositionTest 9 { // main entry point for application static void Main( string[] args ) { Employee e = new Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ); 15 MessageBox.Show( e.ToEmployeeString(), "Testing Class Employee" ); 18 } // end method Main 20 21 } // end class CompositionTest CompositionTest.cs Program Output

34 8.9 Using the this reference
Every object can reference itself by using the keyword this Often used to distinguish between a method’s variables and the instance variables of an object

35 The this reference is used to refer to an instance method
1 // Fig. 8.11: Time4.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time4 class definition 7 public class Time4 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // constructor public Time4( int hour, int minute, int second ) { this.hour = hour; this.minute = minute; this.second = second; } 20 // create string using this and implicit references public string BuildString() { return "this.ToStandardString(): " + this.ToStandardString() + "\nToStandardString(): " + ToStandardString(); } 28 The this reference is used to set the class member variables to the constructor arguments Time4.cs The this reference is used to refer to an instance method

36 The this reference is used to access member variables Time4.cs
// convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( this.hour == 12 || this.hour == 0 ) ? 12 : this.hour % 12 ), this.minute, this.second, ( this.hour < 12 ? "AM" : "PM" ) ); } 37 38 } // end class Time4 The this reference is used to access member variables Time4.cs

37 ThisTest.cs Program Output
1 // Fig. 8.12: ThisTest.cs 2 // Using the this reference. 3 4 using System; 5 using System.Windows.Forms; 6 7 // ThisTest class definition 8 class Class1 9 { // main entry point for application static void Main( string[] args ) { Time4 time = new Time4( 12, 30, 19 ); 14 MessageBox.Show( time.BuildString(), "Demonstrating the \"this\" Reference" ); } 18 } ThisTest.cs Program Output

38 8.10 Garbage Collection Operator new allocates memory When objects are no longer referenced, the CLR performs garbage collection Garbage collection helps avoid memory leaks (running out of memory because unused memory has not been reclaimed) Allocation and deallocation of other resources (database connections, file access, etc.) must be explicitly handled by programmers

39 8.10 Garbage Collection Use finalizers in conjunction with the garbage collector to release resources and memory Before garbage collector reclaims an object’s memory, it calls the object’s finalizer 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

40 8.11 static Class Members Every object of a class has its own copy of all instance variables Sometimes it is useful if all instances 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) Scope may be defined for static variables (public, private, etc.)

41 Update number of Employees
1 // Fig. 8.13: Employee.cs 2 // Employee class contains static data and a static method. 3 4 using System; 5 6 // Employee class definition 7 public class Employee 8 { private string firstName; private string lastName; private static int count; // Employee objects in memory 12 // constructor increments static Employee count public Employee( string fName, string lName ) { firstName = fName; lastName = lName; 18 count; 20 Console.WriteLine( "Employee object constructor: " + firstName + " " + lastName + "; count = " + Count ); } 24 // destructor decrements static Employee count ~Employee() { count; 29 Console.WriteLine( "Employee object destructor: " + firstName + " " + lastName + "; count = " + Count ); } 33 Employee destructor Employee.cs Update number of Employees Decrease static member count, to signify that there is one less employee

42 Employee.cs 34 // FirstName property 35 public string FirstName 36 {
{ get { return firstName; } } 42 // LastName property public string LastName { get { return lastName; } } 51 // static Count property public static int Count { get { return count; } } 60 61 } // end class Employee Employee.cs

43 Create 2 Employee objects
1 // Fig. 8.14: StaticTest.cs 2 // Demonstrating static class members. 3 4 using System; 5 6 // StaticTest class definition 7 class StaticTest 8 { // main entry point for application static void Main( string[] args ) { Console.WriteLine( "Employees before instantiation: " + Employee.Count + "\n" ); 14 // create two Employees Employee employee1 = new Employee( "Susan", "Baker" ); Employee employee2 = new Employee( "Bob", "Jones" ); 18 Console.WriteLine( "\nEmployees after instantiation: " + "Employee.Count = " + Employee.Count + "\n" ); 21 // display the Employees Console.WriteLine( "Employee 1: " + employee1.FirstName + " " + employee1.LastName + "\nEmployee 2: " + employee2.FirstName + " " + employee2.LastName + "\n" ); 27 // mark employee1 and employee1 objects for // garbage collection employee1 = null; employee2 = null; 32 // force garbage collection System.GC.Collect(); 35 Create 2 Employee objects StaticTest.cs Set Employee objects to null Force garbage collection

44 StaticTest.cs Program Output
Console.WriteLine( "\nEmployees after garbage collection: " + Employee.Count ); } 40 } StaticTest.cs Program Output 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: 2

45 8.12 const and readonly 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 Use keyword readonly to declare members who will be initialized in the constructor but not change after that

46 Readonly variable radius; must be initialized in constructor
1 // Fig. 8.15: 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 { // PI is constant variable public const double PI = ; 12 // radius is a constant variable // that is uninitialized public readonly int radius; 16 public Constants( int radiusValue ) { radius = radiusValue; } 21 22 } // end class Constants 23 24 // UsingConstAndReadOnly class definition 25 public class UsingConstAndReadOnly 26 { // method Main creates Constants // object and displays it's values static void Main( string[] args ) { Random random = new Random(); 32 Constants constantValues = new Constants( random.Next( 1, 20 ) ); 35 Readonly variable radius; must be initialized in constructor Constant variable PI UsingConstAndReadOnly.cs Initialize readonly member radius

47 UsingConstAndReadOnly.cs Program Output
MessageBox.Show( "Radius = " + constantValues.radius + "\nCircumference = " + * Constants.PI * constantValues.radius, "Circumference" ); 40 } // end method Main 42 43 } // end class UsingConstAndReadOnly UsingConstAndReadOnly.cs Program Output

48 8.13 Indexers Sometimes a classes encapsulates data which is like a list of elements Indexers are special properties that allow array-style access to the data in the class Indexers can be defined to accept both integer and non-integer subscripts Defined using the keyword this When using indexers, programmers use the bracket ([]) notation, as with arrays, for get and set accessors

49 1 // Fig. 8.10: IndexerTest.cs 2 // Indexers provide access to an object's members via a 3 // subscript operator. 4 5 using System; 6 using System.Drawing; 7 using System.Collections; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Data; 11 12 // Box class definition represents a box with length, 13 // width and height dimensions 14 public class Box 15 { private string[] names = { "length", "width", "height" }; private double[] dimensions = new double[ 3 ]; 18 // constructor public Box( double length, double width, double height ) { dimensions[ 0 ] = length; dimensions[ 1 ] = width; dimensions[ 2 ] = height; } 26 // access dimensions by index number public double this[ int index ] { get { return ( index < 0 || index > dimensions.Length ) ? : dimensions[ index ]; } 35 IndexerTest.cs Indexer declaration; indexer receives an integer to specify which dimension is wanted If the index requested is out of bounds, return –1; otherwise, return the appropriate element The get index accessor

50 Indexer that takes the name of the dimension as an argument
set { if ( index >= 0 && index < dimensions.Length ) dimensions[ index ] = value; } 41 } // end numeric indexer 43 // access dimensions by their names public double this[ string name ] { get { // locate element to get int i = 0; 51 while ( i < names.Length && name.ToLower() != names[ i ] ) i++; 55 return ( i == names.Length ) ? -1 : dimensions[ i ]; } 58 set { // locate element to set int i = 0; 63 while ( i < names.Length && name.ToLower() != names[ i ] ) i++; 67 Indexer that takes the name of the dimension as an argument The set accessor for the index Validate that the user wishes to set a valid index in the array and then set it IndexerTest.cs

51 IndexerTest.cs 68 if ( i != names.Length ) 69 dimensions[ i ] = value;
} 71 } // end indexer 73 74 } // end class Box 75 76 // Class IndexerTest 77 public class IndexerTest : System.Windows.Forms.Form 78 { private System.Windows.Forms.Label indexLabel; private System.Windows.Forms.Label nameLabel; 81 private System.Windows.Forms.TextBox indexTextBox; private System.Windows.Forms.TextBox valueTextBox; 84 private System.Windows.Forms.Button nameSetButton; private System.Windows.Forms.Button nameGetButton; 87 private System.Windows.Forms.Button intSetButton; private System.Windows.Forms.Button intGetButton; 90 private System.Windows.Forms.TextBox resultTextBox; 92 // required designer variable private System.ComponentModel.Container components = null; 95 private Box box; 97 // constructor public IndexerTest() { // required for Windows Form Designer support InitializeComponent(); IndexerTest.cs

52 Use the get accessor of the indexer
103 // create block box = new Box( 0.0, 0.0, 0.0 ); } 107 // Visual Studio .NET generated code 109 // main entry point for application [STAThread] static void Main() { Application.Run( new IndexerTest() ); } 116 // display value at specified index number private void ShowValueAtIndex( string prefix, int index ) { resultTextBox.Text = prefix + "box[ " + index + " ] = " + box[ index ]; } 123 // display value with specified name private void ShowValueAtIndex( string prefix, string name ) { resultTextBox.Text = prefix + "box[ " + name + " ] = " + box[ name ]; } 130 // clear indexTextBox and valueTextBox private void ClearTextBoxes() { indexTextBox.Text = ""; valueTextBox.Text = ""; } 137 Use the get accessor of the indexer IndexerTest.cs Use the set accessor of the indexer

53 Use integer indexer to set value
// get value at specified index private void intGetButton_Click( object sender, System.EventArgs e ) { ShowValueAtIndex( "get: ", Int32.Parse( indexTextBox.Text ) ); ClearTextBoxes(); } 146 // set value at specified index private void intSetButton_Click( object sender, System.EventArgs e ) { int index = Int32.Parse( indexTextBox.Text ); box[ index ] = Double.Parse( valueTextBox.Text ); 153 ShowValueAtIndex( "set: ", index ); ClearTextBoxes(); } 157 // get value with specified name private void nameGetButton_Click( object sender, System.EventArgs e ) { ShowValueAtIndex( "get: ", indexTextBox.Text ); ClearTextBoxes(); } 165 Use integer indexer to set value Use integer indexer to get value IndexerTest.cs Use string indexer to get value

54 IndexerTest.cs Program Output
// set value with specified name private void nameSetButton_Click( object sender, System.EventArgs e ) { box[ indexTextBox.Text ] = Double.Parse( valueTextBox.Text ); 172 ShowValueAtIndex( "set: ", indexTextBox.Text ); ClearTextBoxes(); } 176 177 } // end class IndexerTest Use string indexer to set value IndexerTest.cs Program Output Before setting value by index number After setting value by index number

55 IndexerTest.cs Program Output
Before getting value by dimension name After getting value by dimension name Before setting value by dimension name

56 IndexerTest.cs Program Output
After setting value by dimension name Before getting value by index number After getting value by index number

57 8.14 Data Abstraction and Information Hiding
Classes should hide implementation details Stacks Last-in, first-out (LIFO) Items are pushed onto the top of the stack Items are popped off the top of the stack Queues Similar to a waiting line First-in, first-out (FIFO) Items are enqueued (added to the end) Items are dequeued (taken off the front)

58 The FCL classes should be used whenever possible
8.15 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)

59 TimeLibrary.cs 1 // Fig. 8.17: TimeLibrary.cs
2 // Placing class Time3 in an assembly for reuse. 3 4 using System; 5 6 namespace TimeLibrary 7 { // Time3 class definition public class Time3 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 14 // Time3 constructor initializes instance variables to // zero to set default time to midnight public Time3() { SetTime( 0, 0, 0 ); } 21 // Time3 constructor: hour supplied, minute and second // defaulted to 0 public Time3( int hour ) { SetTime( hour, 0, 0 ); } 28 // Time3 constructor: hour and minute supplied, second // defaulted to 0 public Time3( int hour, int minute ) { SetTime( hour, minute, 0 ); } 35 TimeLibrary.cs

60 36 // Time3 constructor: hour, minute and second supplied
public Time3( int hour, int minute, int second ) { SetTime( hour, minute, second ); } 41 // Time3 constructor: initialize using another Time3 object public Time3( Time3 time ) { SetTime( time.Hour, time.Minute, time.Second ); } 47 // Set new time value in 24-hour format. Perform validity // checks on the data. Set invalid values to zero. public void SetTime( int hourValue, int minuteValue, int secondValue ) { Hour = hourValue; Minute = minuteValue; Second = secondValue; } 57 // property Hour public int Hour { get { return hour; } 65 set { hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); } 70 TimeLibrary.cs

61 TimeLibrary.cs 71 } // end property Hour 72 73 // property Minute
public int Minute { get { return minute; } 80 set { minute = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 85 } // end property Minute 87 // property Second public int Second { get { return second; } 95 set { second = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 100 } // end property Second 102 TimeLibrary.cs

62 103 // convert time to universal-time (24 hour) format string
public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second ); } 109 // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( Hour == 12 || Hour == 0 ) ? 12 : Hour % 12 ), Minute, Second, ( Hour < 12 ? "AM" : "PM" ) ); } 117 } // end class Time3 119 } TimeLibrary.cs

63 8.16 Namespaces and Assemblies
Software components should be reusable 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 Dynamic Link Libraries (.dll files) allow classes to be packaged for reuse

64 8.16 Namespaces and Assemblies
Fig Simple Class Library.

65 AssemblyTest.cs Program Output
1 // Fig. 8.19: AssemblyTest.cs 2 // Using class Time3 from assembly TimeLibrary. 3 4 using System; 5 using TimeLibrary; 6 7 // AssemblyTest class definition 8 class AssemblyTest 9 { // main entry point for application static void Main( string[] args ) { Time3 time = new Time3( 13, 27, 6 ); 14 Console.WriteLine( "Standard time: {0}\nUniversal time: {1}\n", time.ToStandardString(), time.ToUniversalString() ); } 19 } Use Time3 as usual AssemblyTest.cs Program Output Reference the TimeLibrary namespace Standard time: 1:27:06 PM Universal time: 13:27:06

66 8.17 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

67 8.17 Class View and 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 and select Go To Definition

68 8.17 Class View and Object Browser
Fig Class View of class Time1 (Fig. 8.1) and class TimeTest (Fig. 8.2).

69 8.17 Class View and Object Browser
Fig Object Browser when user selects Object from Time1.cs. (part 1)

70 8.17 Class View and Object Browser
Fig Object Browser when user selects Object from Time1.cs. (part 1)


Download ppt "Chapter 8 – Object-Based Programming"

Similar presentations


Ads by Google