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

Slides:



Advertisements
Similar presentations
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
ASP.NET Programming with C# and SQL Server First Edition
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2006 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
 2005 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
1 Object-Based Programming Implementing Multiple Classes Class Scope Controlling Access to Members Initializing Class Objects: Constructors Using Overloaded.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. © by Pearson Education, Inc.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
 2006 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Object-Based Programming Outline 8.1 Introduction 8.2 Implementing a Time Abstract Data Type with.
 2005 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object Oriented Programming
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
Classes, Interfaces and Packages
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Object-Oriented Programming: Classes and Objects.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Classes and Objects: A Deeper Look
C# Object-Oriented Program
Object-Oriented Programming: Classes and Objects
Chapter 16: Classes and Data Abstraction
Chapter 3: Using Methods, Classes, and Objects
Object-Oriented Programming: Classes and Objects
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Object Oriented Programming in java
Chapter 8 – Object-Based Programming
CS360 Client/Server Programming Using Java
More C++ Classes Systems Programming.
Presentation transcript:

Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz,  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.

Jozef Goetz, 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 readonly Instance Variables Data Abstraction and Encapsulation Class View and Object Browser 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.

Jozef Goetz, 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

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

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

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz,  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

Jozef Goetz, 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

Jozef Goetz, 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();

Jozef Goetz, 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

Jozef Goetz,  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

 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; // private int minute; // private int second; // // Time1 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time1() 16 { 17 SetTime( 0, 0, 0 ); 18 } // 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 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.

 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 } // 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 } } // end class Time1 Output time in universal format Output time in standard format

Jozef Goetz, Implementing 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 {

Jozef Goetz, Implementing 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

Jozef Goetz, Implementing 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; // private int minute; // private int second; //

Jozef Goetz, 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()

Jozef Goetz, Implementing 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()

 2002 Prentice Hall. All rights reserved. Outline 21 TimeTest1.cs 1 // Fig. 10.2: TimeTest1.cs 2 // Demonstrating class Time 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; // assign string representation of time to output 17 output = "Initial universal time is: " + 18 time.ToUniversalString() + 19 "\nInitial standard time is: " + 20 time.ToStandardString(); // attempt valid time settings 23 time.SetTime( 13, 27, 6 ); //the reference name specifies // the object that will receive the method call // 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(); // 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.

 2002 Prentice Hall. All rights reserved. Outline output += "\n\nAfter attempting invalid settings: " + 35 "\nUniversal time: " + time.ToUniversalString() + 36 "\nStandard time: " + time.ToStandardString(); MessageBox.Show( output, "Testing Class Time1" ); } // end method Main } // 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.

Jozef Goetz, 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).

Jozef Goetz, 2015

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)

Jozef Goetz, 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

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

Jozef Goetz, 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

Jozef Goetz, 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

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

Jozef Goetz, 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.

Jozef Goetz, 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.

Jozef Goetz, 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

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.

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

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

Jozef Goetz, 2015

<= catch <= try

Jozef Goetz, 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

Jozef Goetz, 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

 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; // private int minute; // private int second; // // Time3 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time3() 16 { 17 SetTime( 0, 0, 0 ); 18 } // Time3 constructor: hour supplied, minute and second 21 // defaulted to 0 22 public Time3( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 } // 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

 2002 Prentice Hall. All rights reserved. Outline // Time3 constructor: hour, minute and second supplied 35 public Time3( int hour, int minute, int second ) 36 { 37 SetTime( hour, minute, second ); 38 } // Time3 constructor: initialize using another Time3 object 41 public Time3( Time3 time ) 42 { 43 SetTime( time.Hour, time.Minute, time.Second ); 44 } // 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 } // 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 } 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

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

 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 // 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 } } // end class Time3

 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; // 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; private System.Windows.Forms.Label minuteLabel; 19 private System.Windows.Forms.TextBox minuteTextBox; 20 private System.Windows.Forms.Button minuteButton; private System.Windows.Forms.Label secondLabel; 23 private System.Windows.Forms.TextBox secondTextBox; 24 private System.Windows.Forms.Button secondButton; private System.Windows.Forms.Button addButton; private System.Windows.Forms.Label displayLabel1; 29 private System.Windows.Forms.Label displayLabel2; // required designer variable 32 private System.ComponentModel.Container components = null; 33

 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(); time = new Time3(); // instantiate a Time3 object 42 UpdateDisplay(); 43 } // Visual Studio.NET generated code // main entry point for application 48 [STAThread] 49 static void Main() 50 { 51 Application.Run( new TimeTest3() ); 52 } // 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

 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 } // 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 } // 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 } // 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

 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; if ( time.Minute == 0 ) 103 time.Hour = ( time.Hour + 1 ) % 24; 104 } UpdateDisplay(); 107 } } // end class TimeTest3

Jozef Goetz, 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.

Jozef Goetz, 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

Jozef Goetz, Date.cs (1, 2 of 4 ) Fig | 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.

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

Jozef Goetz, Outline Date.cs (4 of 4 ) Fig | 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

Jozef Goetz, Class Employee (Fig. 10.8) has instance variables firstName, lastName, birthDate and hireDate. Outline Employee.cs (1 of 2 ) Fig | 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.

Jozef Goetz, Outline Employee.cs (2 of 2 ) Fig | 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

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

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, 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.

Jozef Goetz, 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()

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, Outline Employee.cs (1 of 2 ) Class Employee (Fig ) declares private static variable count and public static property Count. Fig | 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.

Jozef Goetz, Outline Employee.cs (2 of 2 ) Fig | 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

Jozef Goetz, Outline EmployeeTest.cs (1 of 2 ) EmployeeTest method Main (Fig ) instantiates two Employee objects. Fig | 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

Jozef Goetz, Outline EmployeeTest.cs (2 of 2 ) Fig | 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”

 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; count; Console.WriteLine( "Employee object constructor: " + 22 firstName + " " + lastName + "; count = " + Count ); 23 } // 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; 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

 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 } // LastName property 44 public string LastName 45 { 46 get 47 { 48 return lastName; 49 } 50 } // static Count property 53 public static int Count 54 { 55 get 56 { 57 return count; // can access only static members 58 } 59 } } // end class Employee

 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" ); // create two Employees 16 Employee employee1 = new Employee( "Susan", "Baker" ); 17 Employee employee2 = new Employee( "Bob", "Jones" ); Console.WriteLine( "\nEmployees after instantiation: " + 20 "Employee.Count = " + Employee.Count + "\n" ); // display the Employees 23 Console.WriteLine( "Employee 1: " + 24 employee1.FirstName + " " + employee1.LastName + 25 "\nEmployee 2: " + employee2.FirstName + 26 " " + employee2.LastName + "\n" ); // mark employee1 and employee1 objects for 29 // garbage collection 30 employee1 = null; 31 employee2 = null; // 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

 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

Jozef Goetz, 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 = ;

Jozef Goetz, 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.

 2002 Prentice Hall. All rights reserved. Outline 74 UsingConstAndRea dOnly.cs 1 // Fig ed1 (see 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 = ; // initialized at compile time 12 // const is treated as staic // radius is a constant variable 14 // that is uninitialized; initialized at execution time: 15 public readonly int radius; // when program creates Constants obj public Constants( int radiusValue ) 18 { 19 radius = radiusValue; 20 } } // end class Constants // 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(); 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

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

Jozef Goetz, 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

Jozef Goetz, 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)

Jozef Goetz, 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

Jozef Goetz, 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.

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, Outline  Time1.cs

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

Jozef Goetz, Outline  Time1NamespaceTest.cs

Jozef Goetz, 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

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

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

Jozef Goetz, 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 Class View of class Time1 and class TimeTest

Jozef Goetz, 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

Jozef Goetz, Fig | Object Browser for class Math.

Jozef Goetz, 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 ed3) in which we did not define any constructors. Fig | Time class declaration maintains the time in 24-hour format. (Part 1 of 4.) Object Initializers

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

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

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

Jozef Goetz, Outline ObjectInitializer Test.cs (1 of 2 ) Figure ed3 demonstrates object initializers. Fig | 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

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

Jozef Goetz, 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.