csc 330 objectcsc 330 object-oriented programming · 61 ti t st d dst i +time.tostandardstring() +...

31
CSC 330 Object-Oriented CSC 330 Object-Oriented Programming Encapsulation Encapsulation

Upload: others

Post on 05-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

CSC 330 Object-OrientedCSC 330 Object-Oriented Programming

EncapsulationEncapsulationpp

Page 2: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Implementing Data Encapsulation using P tiProperties

Use C# properties to provide access to data safelydata members should be declared private with public propertiesdata members should be declared private, with public properties that allow safe access to themYou access the properties of a class as if you were accessing a data fieldfield Properties do not designate storage locations. Instead, properties have accessors that read, write, or compute their values.

Public properties allow clients to:Get (obtain the values of) private data

• get accessor: controls formatting and retrieval of dataSet (assign values to) private data

• set accessor: ensure that the new value is appropriate for the data

2

pp pmember

Page 3: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Syntax of PropertiesSyntax of PropertiesSyntax of PropertiesSyntax of Properties[attributes] [modifiers][attributes] [modifiers] type identifier {accessor-declaration} [attributes] [modifiers][attributes] [modifiers] type interface-type.identifier {accessor-declaration}yp yp { }where

attributes (OptionalOptional)Additional declarative information. For more information on attributes and attribute classes, see C# Attributes.

modifiers (OptionalOptional)The allowed modifiers are new, static, virtual, abstract, override, and a valid combination of the four access modifiers.

typeTh hi h b l ibl h i lf FThe property type, which must be at least as accessible as the property itself. For more information on accessibility levels, see Access Modifiers.

identifierThe property name. For more information on interface member implementation, see interfaceinterface.

accessor-declarationDeclaration of the property accessors, which are used to read and write the property.

interface-typeThe interface in a fully qualified property name See Interface Properties

3

The interface in a fully qualified property name. See Interface Properties.

Page 4: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Example:Person class that has two properties: Name (string) and Age (int) Both properties are read/write(string) and Age (int). Both properties are read/write.// person.csusing System;class Person{

public override string ToString(){

" " " A " A{private string myName ="N/A";private int myAge = 0;

// Declare a Name property of type string:public string Name{

return "Name = " + Name + ", Age = " + Age;}

public static void Main(){

Console.WriteLine("Simple Properties");

get {

return myName; }set {

myName = value;

// Create a new Person object:Person person = new Person();

// Print out the name and the age associated with the person:Console.WriteLine("Person details - {0}", person);

myName = value; }

}

// Declare an Age property of type int:public int Age{

// Set some values on the person object:person.Name = "Joe";person.Age = 99;Console.WriteLine("Person details - {0}", person);

// Increment the Age property:person Age += 1;get

{ return myAge;

}set {

myAge = value;

person.Age += 1;Console.WriteLine("Person details - {0}", person);

}}

4

myAge = value; }

}

Page 5: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Code DiscussionsCode DiscussionsCode DiscussionsCode Discussions

Notice the way that the properties are declared, for example, consider the NameNameproperty:The setset and getget methods of a property are contained inside the property declaration. You

l h hcan control whether a property is read/write, read-only, or write-only by controlling whether a getget or setset method iswhether a getget or setset method is included.

5

Page 6: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Code Discussions cont’dCode Discussions cont’dCode Discussions cont dCode Discussions cont d

Once the properties are declared, they can be used as if they were fields of the class. This allows for a very natural syntax when both getting and setting the value of agetting and setting the value of a propertyNote that in a property setset method a special valuevalue variable is available. This variable contains the value that the user specifiedNotice the clean syntax for incrementing the AgeAge property on aincrementing the AgeAge property on a PersonPerson object

6

Page 7: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Code Discussions cont’dCode Discussions cont’dCode Discussions cont dCode Discussions cont d

If separate SetSet and GetGet methods were used to model properties, the equivalent code might look like this:

person.SetAge(person.GetAge() + 1);

The ToString ToString method is overridden in this example:Notice that ToStringToString is not explicitly used in the program. It is invoked by default by the WriteLineWriteLine calls.

public override string ToString() {

return "Name = " + Name + ", Age = " + Age;

}

7

Page 8: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Output: Example PersonPerson classOutput: Example PersonPerson class

Simple PropertiesPerson details - Name = N/A, Age = 0Person details - Name = Joe, Age = 99Person details - Name = Joe, Age = 100

8

Page 9: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time3 cs

1 // Time3.cs2 // Class Time2 provides overloaded constructors.3 4 using System; Time3.csg y5 6 // Time3 class definition7 public class Time38 {9 private int hour; // 0-2310 i i i // 0 5910 private int minute; // 0-5911 private int second; // 0-5912 13 // Time3 constructor initializes instance variables to 14 // zero to set default time to midnight15 public Time3()15 public Time3()16 {17 SetTime( 0, 0, 0 );18 }19 20 // Time3 constructor: hour supplied, minute and second21 // defaulted to 022 public Time3( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 }2626 27 // Time3 constructor: hour and minute supplied, second28 // defaulted to 029 public Time3( int hour, int minute ) 30 { 31 SetTime( hour, minute, 0 );31 SetTime( hour, minute, 0 );32 }33

Page 10: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time3 cs

34 // Time3 constructor: hour, minute and second supplied35 public Time3( int hour, int minute, int second ) 36 { 37 SetTime( hour, minute, second ); Time3.cs( , , )38 }39 40 // Time3 constructor: initialize using another Time3 object41 public Time3( Time3 time )42 {43 i ( i i i i d )

Property Hour

43 SetTime( time.Hour, time.Minute, time.Second );44 }45 46 // Set new time value in 24-hour format. Perform validity47 // checks on the data. Set invalid values to zero.48 public void SetTime(48 public void SetTime( 49 int hourValue, int minuteValue, int secondValue )50 {51 Hour = hourValue; 52 Minute = minuteValue;53 Second = secondValue;

Constructor that takes another Time3 object as an argument. New

54 }56 // property Hour57 public int Hour58 {59 get60 {

e3 objec as a a gu e . NewTime3 object is initialized with the values of the argument.

60 {61 return hour;62 }63 64 set65 {65 {66 hour = ( ( value >= 0 && value < 24 ) ? value : 0 );67 }68 } // end property Hour

Page 11: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time3 cs

71 // property Minute72 public int Minute73 {74 get

Property SecondTime3.csg

75 {76 return minute;77 }78 79 set80 { P t Mi t80 {81 minute = ( ( value >= 0 && value < 60 ) ? value : 0 );82 }83 84 } // end property Minute85

Property Minute

85 86 // property Second87 public int Second88 {89 get90 {91 return second;92 }93 94 set95 {96 d ( ( l > 0 && l < 60 ) ? l 0 )96 second = ( ( value >= 0 && value < 60 ) ? value : 0 );97 }98 99 } // end property Second100

Page 12: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time3 cs

101 // convert time to universal-time (24 hour) format string102 public string ToUniversalString()103 {104 return String.Format( Time3.csg (105 "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second );106 }107 108 // convert time to standard-time (12 hour) format string109 public string ToStandardString()110 {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 } 115115 116 } // end class Time3

Page 13: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 cs

1 // TimeTest3.cs2 // Demonstrating Time3 properties Hour, Minute and Second.3 4 using System; TimeTest3.csg y5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;1010 11 // TimeTest3 class definition12 public class TimeTest3 : System.Windows.Forms.Form13 {14 private System.Windows.Forms.Label hourLabel;15 private System Windows Forms TextBox hourTextBox;15 private System.Windows.Forms.TextBox hourTextBox;16 private System.Windows.Forms.Button hourButton;17 18 private System.Windows.Forms.Label minuteLabel;19 private System.Windows.Forms.TextBox minuteTextBox;20 private System.Windows.Forms.Button minuteButton;21 22 private System.Windows.Forms.Label secondLabel;23 private System.Windows.Forms.TextBox secondTextBox;24 private System.Windows.Forms.Button secondButton;25 26 i t S t Wi d F B tt ddB tt26 private System.Windows.Forms.Button addButton;27 28 private System.Windows.Forms.Label displayLabel1;29 private System.Windows.Forms.Label displayLabel2;30 31 // required designer variable31 // required designer variable32 private System.ComponentModel.Container components = null;33 34 private Time3 time;35

Page 14: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 cs

36 public TimeTest3()37 {38 // Required for Windows Form Designer support39 InitializeComponent(); TimeTest3.csp ()40 41 time = new Time3();42 UpdateDisplay();43 }44 45 // i l di d d45 // Visual Studio .NET generated code46 47 // main entry point for application48 [STAThread]49 static void Main() 50 {50 {51 Application.Run( new TimeTest3() );52 }53 54 // update display labels55 public void UpdateDisplay()56 {57 displayLabel1.Text = "Hour: " + time.Hour + 58 "; Minute: " + time.Minute +59 "; Second: " + time.Second;60 displayLabel2.Text = "Standard time: " +61 ti T St d dSt i () + "\ U i l ti " +61 time.ToStandardString() + "\nUniversal time: " +62 time.ToUniversalString();63 }64

Page 15: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 cs

65 // set Hour property when hourButton pressed66 private void hourButton_Click( 67 object sender, System.EventArgs e )68 {

Set Minute property of Time3 object TimeTest3.cs{

69 time.Hour = Int32.Parse( hourTextBox.Text );70 hourTextBox.Text = "";71 UpdateDisplay();72 }73 74 // i h i d

j

Set Second property of Time3 object

74 // set Minute property when minuteButton pressed75 private void minuteButton_Click(76 object sender, System.EventArgs e )77 {78 time.Minute = Int32.Parse( minuteTextBox.Text );79 minuteTextBox Text = "";

Set Hour property of Time3 object

79 minuteTextBox.Text = ;80 UpdateDisplay();81 }82 83 // set Second property when secondButton pressed84 private void secondButton_Click(

Add 1 second to Time3 object

_85 object sender, System.EventArgs e )86 {87 time.Second = Int32.Parse( secondTextBox.Text );88 secondTextBox.Text = "";89 UpdateDisplay(); 90 }90 }91 92 // add one to Second when addButton pressed93 private void addButton_Click(94 object sender, System.EventArgs e )95 {95 {96 time.Second = ( time.Second + 1 ) % 60;97

Page 16: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 cs

98 if ( time.Second == 0 )99 {100 time.Minute = ( time.Minute + 1 ) % 60;101 TimeTest3.cs102 if ( time.Minute == 0 )103 time.Hour = ( time.Hour + 1 ) % 24;104 }105 106 UpdateDisplay();107 }

Program O tp t

107 }108 109 } // end class TimeTest3

Program Output

Page 17: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 csTimeTest3.csProgram Output

Page 18: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

TimeTest3 csTimeTest3.csProgram Output

Page 19: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

19

Using the this reference

• Every object can reference itself by using the keyword thiskeyword this

• Often used to distinguish between a method’s variables and the instance variables of an objectvariables and the instance variables of an object

Page 20: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time4 cs

1 // Time4.cs2 // Class Time2 provides overloaded constructors.3 4 using System; The this reference is used to set the Time4.csg y5 6 // Time4 class definition7 public class Time4 8 {9 private int hour; // 0-2310 i i i // 0 59

The this reference is used to set the class member variables to the constructor arguments

10 private int minute; // 0-5911 private int second; // 0-5912 13 // constructor14 public Time4( int hour, int minute, int second ) 15 {

The this reference is used to refer to an instance method

15 { 16 this.hour = hour;17 this.minute = minute;18 this.second = second;19 }20 21 // create string using this and implicit references22 public string BuildString()23 {24 return "this.ToStandardString(): " + 25 this.ToStandardString() + 26 "\ T St d dSt i () " + T St d dSt i ()26 "\nToStandardString(): " + ToStandardString();27 }28

Page 21: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Time4 cs

29 // convert time to standard-time (12 hour) format string30 public string ToStandardString()31 {32 return String.Format( "{0}:{1:D2}:{2:D2} {3}", Time4.csg ( { } { } { } { } ,33 ( ( this.hour == 12 || this.hour == 0 ) ? 12 : 34 this.hour % 12 ), this.minute, this.second,35 ( this.hour < 12 ? "AM" : "PM" ) );36 } 37 38 } // d l i 438 } // end class Time4 The this reference is used to

access member variables

Page 22: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

ThisTest cs

1 // Fig. 8.12: ThisTest.cs2 // Using the this reference.3 4 using System; ThisTest.csg y5 using System.Windows.Forms;6 7 // ThisTest class definition8 class Class19 {10 // i i f li i10 // main entry point for application11 static void Main( string[] args )12 {13 Time4 time = new Time4( 12, 30, 19 );14 15 MessageBox Show( time BuildString()15 MessageBox.Show( time.BuildString(), 16 "Demonstrating the \"this\" Reference" );17 }18 }

Program Output

Page 23: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

23

Garbage Collection

• Operator new allocates memoryWhen objects are no longer referenced the• When objects are no longer referenced, the Common Language Runtime (CLR) performs garbage collectiongarbage collection

• Garbage collection helps avoid memory leaks (running out of memory because unused memory ( u g ou o e o y bec use u used e o yhas not been reclaimed)

• Allocation and deallocation of other resources (database connections, file access, etc.) must be explicitly handled by programmers

Page 24: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

24

static Class Members

• Every object of a class has its own copy of all instance variablesinstance variables

• Sometimes it is useful if all instances of a class share the same copy of a variableshare the same copy of a variable

• Declare variables using keyword static to create only one copy of the variable at a time (shared by o y o e copy o e v b e e (s ed byall objects of the type)

• Scope may be defined for static variables (public, p y (p ,private, etc.)

Page 25: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Employee cs

1 // Employee.cs2 // Employee class contains static data and a static method.3 4 using System; E l d t t Employee.csg y5 6 // Employee class definition7 public class Employee8 {9 private string firstName;10 i i l

Employee destructor

Decrease static member count to signify that there

Update number of Employees

10 private string lastName;11 private static int count; // Employee objects in memory12 13 // constructor increments static Employee count14 public Employee( string fName, string lName )15 {

count, to signify that there is one less employee

15 {16 firstName = fName;17 lastName = lName;18 19 ++count;20 21 Console.WriteLine( "Employee object constructor: " +22 firstName + " " + lastName + "; count = " + Count ); 23 }24 25 // destructor decrements static Employee count26 E l ()26 ~Employee()27 {28 --count;29 30 Console.WriteLine( "Employee object destructor: " +31 firstName + " " + lastName + "; count = " + Count );31 firstName + + lastName + ; count + Count );32 }33

Page 26: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

Employee cs

34 // FirstName property35 public string FirstName36 {37 get Employee.csg38 {39 return firstName;40 }41 }42 43 //43 // LastName property44 public string LastName45 {46 get47 {48 return lastName;48 return lastName;49 }50 }51 52 // static Count property53 public static int Count54 {55 get56 {57 return count;58 }59 }59 }60 61 } // end class Employee

Page 27: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

StaticTest cs

1 // StaticTest.cs2 // Demonstrating static class members.3 4 using System;

Create 2 Employee objects

StaticTest.csg y5 6 // StaticTest class definition7 class StaticTest8 {9 // main entry point for application10 i id i ( i [] )

Set Employee objects to null10 static void Main( string[] args )11 {12 Console.WriteLine( "Employees before instantiation: " +13 Employee.Count + "\n" );14 15 // create two Employees

Force garbage collection

15 // create two Employees16 Employee employee1 = new Employee( "Susan", "Baker" );17 Employee employee2 = new Employee( "Bob", "Jones" );18 19 Console.WriteLine( "\nEmployees after instantiation: " +20 "Employee.Count = " + Employee.Count + "\n" );21 22 // display the Employees 23 Console.WriteLine( "Employee 1: " + 24 employee1.FirstName + " " + employee1.LastName +25 "\nEmployee 2: " + employee2.FirstName +26 " " + l 2 L tN + "\ " )26 " " + employee2.LastName + "\n" );27 28 // mark employee1 and employee1 objects for 29 // garbage collection30 employee1 = null;31 employee2 = null;31 employee2 null;32 33 // force garbage collection34 System.GC.Collect();35

Page 28: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

StaticTest cs

36 Console.WriteLine( 37 "\nEmployees after garbage collection: " +38 Employee.Count );39 } StaticTest.cs

P O t t

}40 }

Employees before instantiation: 0 Program Outputp y

Employee object constructor: Susan Baker; count = 1Employee object constructor: Bob Jones; count = 2

Employees after instantiation: Employee.Count = 2

Employee 1: Susan BakerEmployee 2: Bob Jones

Employee object destructor: Bob Jones; count = 1Employee object destructor: Susan Baker; count = 0Employee object destructor: Susan Baker; count = 0

Employees after garbage collection: 2

Page 29: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

29

const and readonly Members

• Declare constant members (members whose value will never change) using the keyword constwill never change) using the keyword const

• const members are implicitly static• const members must be initialized when they are• const members must be initialized when they are

declared• Use keyword readonly to declare members who• Use keyword readonly to declare members who

will be initialized in the constructor but not change after that

Page 30: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

UsingConstAndRea

1 // UsingConstAndReadOnly.cs2 // Demonstrating constant values with const and readonly.3 4 using System; Constant variable PI

Readonly variable radius; must be initialized in constructor UsingConstAndRea

dOnly.cs

g y5 using System.Windows.Forms;6 7 // Constants class definition8 public class Constants9 {10 // i i bl

Constant variable PI

Initialize readonly member radius

10 // PI is constant variable11 public const double PI = 3.14159;12 13 // radius is a constant variable14 // that is uninitialized15 public readonly int radius;15 public readonly int radius;16 17 public Constants( int radiusValue )18 {19 radius = radiusValue;20 }21 22 } // end class Constants23 24 // UsingConstAndReadOnly class definition25 public class UsingConstAndReadOnly26 {26 {27 // method Main creates Constants 28 // object and displays it's values29 static void Main( string[] args )30 { 31 Random random = new Random();31 Random random new Random();32 33 Constants constantValues = 34 new Constants( random.Next( 1, 20 ) );35

Page 31: CSC 330 ObjectCSC 330 Object-Oriented Programming · 61 ti T St d dSt i +time.ToStandardString() + "\nUUi lti "niversal time: " + 62 time.ToUniversalString(); 63 } 64 . Outline TimeTest3

Outline

UsingConstAndRea

36 MessageBox.Show( "Radius = " + constantValues.radius + 37 "\nCircumference = " + 38 2 * Constants.PI * constantValues.radius,39 "Circumference" ); UsingConstAndRea

dOnly.cs

)40 41 } // end method Main42 43 } // end class UsingConstAndReadOnly

Program Output