Title: CS 112 Introduction to Programming
1CS 112 Introduction to Programming
- Lecture 17
- Object Life Cycle static, readonly, this
- Http//zoo.cs.yale.edu/classes/cs112/
2Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
3Admin.
- Assignment 3
- If you have time, you can try to run your deign
with a TA or with me - This is called design review
- Part 1 PowerMod
- You can write a straightforward version or use
the pseudo code - It will be an interesting exercise to compare the
performance of these two implementations - Midterm 1
- Topics
- lectures 1 21
- a list of topics will be posted by this weekend
- Samples linked on the schedule page
4Recap Encapsulation and Public and Private
Accessibility
private
public
violate Encapsulation Unless properties
enforce encapsulation
variables
provide services to clients
support other methods in the class
methods
Example a different implementation of Time3.
see Time3.cs of previous lecture
5Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
6Object Life Cycle
- Operator new allocates memory
- Constructor initializes the state
- Assigned to a variable declared with the class as
the type - the object is referenced by the variable, e.g.,
Time1 t1 new Time1(11, 45, 59) - An object may be referenced by multiple
variables, e.g., Time1 t2 t1 - An object may be referenced by no variable (the
object is a garbage)e.g., t1 new
Time1(12, 55, 50) t2 null
7Garbage Collection
- When objects are no longer referenced, the C
Language Runtime (CLR) performs garbage
collection - Garbage collection avoids 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
8Garbage Collection
- You can use finalizers in conjunction with the
garbage collector to release resources and memory - Before garbage collector reclaims an objects
memory, it automatically calls the objects
finalizer - Each class has only at most one finalizer (also
called destructor) - Name of a destructor is the character, followed
by the class name - Destructors do not receive any arguments
See TimeLifeCycle.cs and Time3.cs of the project
9Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
10static 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) - Static class members
- static data
- can be accessed in instance methods and static
methods - static methods
- invocation ClassName.MethodName( )
- can only access static data of the class
- Question why not instance data?
See Employee.cs and StaticTest.cs
11Employee.cs
- 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
- 9 private string firstName
- 10 private string lastName
- 11 private static int count // Employee
objects in memory - 12
- 13 // constructor increments static Employee
count - 14 public Employee( string fName, string
lName ) - 15
- 16 firstName fName
- 17 lastName lName
- 18
- 19 count
Employee destructor
Decrease static member count, to signify that
there is one less employee
12Employee.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
13StaticTest.cs
- 1 // Fig. 8.14 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 "
Create 2 Employee objects
Set Employee objects to null
14StaticTest.cs Program Output
- 36 // wait until collection completes
for demo only - System.GC.WaitForPendingFinalizers()
-
- 39 Console.WriteLine(
- 40 "\nEmployees after garbage
collection " - 41 Employee.Count )
- 42
- 43
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
15Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
16const 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
See UsingConstAndReadonly.cs
17UsingConstAndReadOnly.cs
- 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
- 10 // PI is constant variable
- 11 public const double PI 3.14159
- 12
- 13 // radius is a constant variable
- 14 // that is uninitialized
- 15 public readonly int radius
- 16
- 17 public Constants( int radiusValue )
- 18
- 19 radius radiusValue
Readonly variable radius must be initialized in
constructor
Initialize readonly member radius
18UsingConstAndReadOnly.cs Program Output
- 36 MessageBox.Show( "Radius "
constantValues.radius - 37 "\nCircumference "
- 38 2 Constants.PI
constantValues.radius, - 39 "Circumference" )
- 40
- 41 // end method Main
- 42
- 43 // end class UsingConstAndReadOnly
19Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
20Using the this reference
- Every object can reference itself by using the
keyword this - Often used to distinguish between a methods
variables and the instance variables of an object - e.g., in constructors
See Time4.cs and ThisTest.cs
21Time4.cs
- 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
- 9 private int hour // 0-23
- 10 private int minute // 0-59
- 11 private int second // 0-59
- 12
- 13 // constructor
- 14 public Time4( int hour, int minute, int
second ) - 15
- 16 this.hour hour
- 17 this.minute minute
- 18 this.second second
- 19
22Time4.cs
- 29 // convert time to standard-time (12
hour) format string - 30 public string ToStandardString()
- 31
- 32 return String.Format(
"01D22D2 3", - 33 ( ( this.hour 12 this.hour
0 ) ? 12 - 34 this.hour 12 ), this.minute,
this.second, - 35 ( this.hour lt 12 ? "AM" "PM" ) )
- 36
- 37
- 38 // end class Time4
23ThisTest.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
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 Time4 time new Time4( 12, 30, 19 )
- 14
- 15 MessageBox.Show( time.BuildString(),
- 16 "Demonstrating the
\"this\" Reference" ) - 17
- 18
24Backup Slides
25Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
- Two more examples
- Rational
- Using objects to draw multiple figures
26Rational
- How to represent rational numbers such as ½, ¾?
- What methods does a rational number need to
support?
See Rational.cs and RationalNumbers.cs
27Outline
- Admin. and review
- More language structures
- object life cycle and finalizer/destructor
- static members
- const and readonly members
- using this reference
- Two more examples
- Rational
- Using objects to draw multiple figures
28Graphics Drawing Shapes Using the Graphics
class
- Create a Windows application
- In the OnPaint() method, draw any objects you
want - Many methods to draw different shapesDrawString(
string str, Font f, SolidBrush b, int x, int y)
DrawLine(Pen p, int x1, int y1, int x2, int
y2)DrawEllipse(Pen p, int x, int y, int width,
int height)
C uses a coordinate system with the origin at
the upper left corner
29Example Drawing a Line
10
150
20
45
30Example Drawing a Rectangle
50
20
page.DrawRectangle (p, 50, 20, 100, 40)
31The Color Class
- A color is defined in a program using an object
created from the Color class - The Color class also contains several static
predefined colors
32Using Objects to Draw Figures
See StickFigure.cs and LineUp.cs