Title: ObjectBased Programming :
1Object-Based Programming Part 1 (Dietel,
Chapter 8)
2Definitions
- Encapsulation a wrapping together of data
(attributes) and methods (behaviors) - Information Hiding the ability of an object to
hide its implementation from other objects - Interface the mechanism through which objects
communicate with one another in lieu of each of
the objects internal implementations. - Class the unit of programming in C.
- Function the unit of programming in a
procedural programming language such as VB, C,
FORTRAN. - Methods a function in C.
- Instantiation the run-time realization of a
class into an object.
3Abstract Data Type -Definition
- Classes in C facilitate the creation of abstract
data types (ADT) - An ADT hides its implementation from clients or
users of the instantiated object. - Using ADTs overcomes procedural language
limitations on data dependency. - It is important to write programs that are
understandable and easy to maintain. Change is
the rule rather than the exception.
4Abstract Data Type ExampleDownloadable Source
Code
- // Class Time1 maintains time in 24-hour format.
- using System
- namespace TimeTest1
-
- // Time1 class definition
- public class Time1 Object // this is
redundant -
- private int hour // 0 -23
- private int minute // 0-59
- private int second // 0-59
- // Time1 constructor initializes instance
variables to - // zero to set default time to midnight
- public Time1()
-
- SetTime( 0, 0, 0 )
-
minute ( minuteValue gt 0 minuteValue lt 60 )
? minuteValue 0 second
( secondValue gt 0 secondValue lt 60 ) ?
secondValue 0 // end method
SetTime // convert time to universal-time
(24 hour) format string public string
ToUniversalString() return
String.Format( "0D21D22D2"
, hour, minute, second ) //
convert time to standard-time (12 hour) format
string public string ToStandardString()
return String.Format(
"01D22D2 3", ( ( hour
12 hour 0 ) ? 12 hour 12 ),
minute, second, ( hour lt 12 ? "AM" "PM" ) )
// end class Time1
5Instantiating the Class Using the dot
notationDownloadable Source Code
- // Demonstrating class Time1.
- using System
- using System.Windows.Forms
- namespace TimeTest1
-
- // TimeTest1 uses creates and uses a Time1
object - class TimeTest1
-
- // main entry point for application
- static void Main( string args )
-
- Time1 time new Time1() // calls
Time1 constructor - string output
- // assign string representation of time
to output - output "Initial universal time is "
- time.ToUniversalString()
// append new string representations of time to
output output "\n\nUniversal time
after SetTime is "
time.ToUniversalString()
"\nStandard time after SetTime is "
time.ToStandardString() // attempt
invalid time settings time.SetTime( 99,
99, 99 ) output "\n\nAfter
attempting invalid settings "
"\nUniversal time " time.ToUniversalString()
"\nStandard time "
time.ToStandardString()
MessageBox.Show( output, "Testing Class Time1"
) // end method Main // end
class TimeTest1
6Class Scope
- The scope (declaration space) of an identifier
for a variable, reference, method, or class is
the portion of the program in which the
identifier can be accessed. A local variable
declared in a block can be used only within that
block i.e. between . - Members of a class have class scope and are
visible in what is known as the declaration space
of a class. - Class scope begins at the beginning left brace
() of the class definition and terminates at the
closing right brace (). - Class scope enables methods of a class to access
all members defined in that class. - Static members are an exception to this rule.
- All instance variables and methods of a class are
global to the methods of the class in which they
are defined.
7Controlling Access to Members
- The member access modifiers public and private
control access to a classs data and methods. - Public methods present to the classs clients a
view of the services that the class provides.
This is the public interface of the class. - Private class members are not accessible outside
the class. - Access to private data should be controlled
carefully by a classs methods. To allow clients
to read the values of private data, the class can
define a property that enables client code to
access the private data safely. Weve already
discussed accessor (get) and mutator (set)
methods. - The following code example shows how attempting
to access private class members generates syntax
errors. To prove this, create a a C.NET project
and add these existing files to the project. Try
building the project and running it. - 1. Restricted access demo C source code
- 2. Time1 class
8Initializing Class Objects Constructors
- When a program creates an instance of a class,
the program invokes the classs constructor to
initialize the classs instance variables (data
members). - A class can contain overloaded constructors to
provide multiple ways to initialize objects of
that class. - Instance variables can be initialized either by a
constructor or when they are declared in the
class body. - Regardless of whether instance variables receive
explicit initialization values, the instance
variables are always initialized. In such cases,
instance variables receive their default values - 0 for primitive numeric type variables
- false for bool variables
- null for references.
9Using Overloaded Constructors (cont)
- // Class Time2 provides overloaded constructors.
- using System
- namespace TimeTest2
-
- // Time2 class definition
- public class Time2 Object
-
- private int hour // 0-23
- private int minute // 0-59
- private int second // 0-59
- // Time2 constructor initializes instance
variables to - // zero to set default time to midnight
- public Time2()
-
- SetTime( 0, 0, 0 )
-
// Time2 constructor hour and minute supplied,
second // defaulted to 0 public
Time2( int hour, int minute )
SetTime( hour, minute, 0 ) //
Time2 constructor hour, minute and second
supplied public Time2( int hour, int
minute, int second ) SetTime(
hour, minute, second ) // Time2
constructor initialize using another Time2
object public Time2( Time2 time )
SetTime( time.hour, time.minute,
time.second )
10Using Overloaded Constructors
- // 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 gt 0 hourValue lt
24 ) ? - hourValue 0
- minute ( minuteValue gt 0
minuteValue lt 60 ) ? - minuteValue 0
- second ( secondValue gt 0
secondValue lt 60 ) ? - secondValue 0
-
- // convert time to universal-time (24 hour)
format string - public string ToUniversalString()
-
- return String.Format(
- "0D21D22D2", hour, minute,
second ) -
11Calling Overloaded ConstructorsTime2.csTimeTest2
.cs
- // Using overloaded constructors.
- using System
- using System.Windows.Forms
- namespace TimeTest2
-
- // TimeTest2 demonstrates constructors of
class Time2 - class TimeTest2
-
- // main entry point for application
- static void Main(string args)
-
- Time2 time1, time2, time3, time4, time5,
time6 - time1 new Time2() //
000000 - time2 new Time2( 2 ) //
020000 - time3 new Time2( 21, 34 ) //
213400 - time4 new Time2( 12, 25, 42 ) //
122542
output "\ntime2 hour specified minute and "
"second defaulted"
"\n\t" time2.ToUniversalString()
"\n\t" time2.ToStandardString()
output "\ntime3 hour and minute specified "
"second defaulted"
"\n\t" time3.ToUniversalString()
"\n\t" time3.ToStandardString()
output "\ntime4 hour, minute, and second
specified" "\n\t"
time4.ToUniversalString() "\n\t"
time4.ToStandardString() output
"\ntime5 all invalid values specified"
"\n\t" time5.ToUniversalString()
"\n\t" time5.ToStandardString()
output "\ntime6 Time2 object time4 specified"
"\n\t" time6.ToUniversalString()
"\n\t" time6.ToStandardString()
MessageBox.Show( output,
"Demonstrating Overloaded Constructors" )
// end method Main // end class
TimeTest2
12Properties Optional (cont)This portion of the
lecture will involve class participation in using
the IDE to build a simple GUI.Time3.cs,
TimeTest3.cs
- // Class Time2 provides overloaded constructors.
- using System
- namespace TimeTest3
-
- // Time3 class definition
- public class Time3 Object
-
- private int hour // 0-23
- private int minute // 0-59
- private int second // 0-59
- // Time3 constructor initializes instance
variables to - // zero to set default time to midnight
- public Time3()
-
- SetTime( 0, 0, 0 )
-
// Time3 constructor hour and minute supplied,
second // defaulted to 0 public
Time3( int hour, int minute )
SetTime( hour, minute, 0 ) //
Time3 constructor hour, minute and second
supplied public Time3( int hour, int
minute, int second ) SetTime(
hour, minute, second ) // Time3
constructor initialize using another Time3
object public Time3( Time3 time )
SetTime( time.Hour, time.Minute,
time.Second ) // 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 // invoke
Hour property set Minute minuteValue
// invoke Minute property set Second
secondValue // invoke Second property set
13Properties Optional (cont)
- // property Hour
- public int Hour
-
- get
-
- return hour
-
- set
-
- hour ( ( value gt 0 value lt 24 )
? value 0 ) -
- // end property Hour
- // property Minute
- public int Minute
-
- get
// property Second public int Second
get return
second set
second ( ( value gt 0 value lt
60 ) ? value 0 ) // end
property Second // convert time to
universal-time (24 hour) format string
public string ToUniversalString()
return String.Format(
"0D21D22D2", Hour, Minute, Second )
// convert time to standard-time (12
hour) format string public string
ToStandardString() return
String.Format( "01D22D2 3",
( ( Hour 12 Hour 0 ) ? 12 Hour 12
), Minute, Second, ( Hour lt 12 ? "AM"
"PM" ) ) // end class
Time3
14Using Properties Optional (cont)
- using System
- using System.Drawing
- using System.Collections
- using System.ComponentModel
- using System.Windows.Forms
- using System.Data
- namespace TimeTest3
-
- // TimeTest3 class definition
- public class TimeTest3 System.Windows.Forms.F
orm -
- private System.Windows.Forms.Label
hourLabel - private System.Windows.Forms.TextBox
hourTextBox - private System.Windows.Forms.Button
hourButton - private System.Windows.Forms.Label
minuteLabel - private System.Windows.Forms.TextBox
minuteTextBox - private System.Windows.Forms.Button
minuteButton
// required designer variable private
System.ComponentModel.Container components
null private Time3 time public
TimeTest3() // Required for
Windows Form Designer support
InitializeComponent() time new
Time3() UpdateDisplay()
/// ltsummarygt /// Clean up any resources
being used. /// lt/summarygt protected
override void Dispose( bool disposing )
if( disposing ) if
(components ! null)
components.Dispose()
base.Dispose( disposing )
region Windows Form Designer generated
code /// ltsummarygt /// Required
method for Designer support - do not modify
15Using Properties Optional
- /// the contents of this method with the code
editor. - /// lt/summarygt
- private void InitializeComponent()
-
- this.hourLabel new System.Windows.Forms
.Label() - this.minuteLabel new
System.Windows.Forms.Label() - this.secondLabel new
System.Windows.Forms.Label() - this.hourTextBox new
System.Windows.Forms.TextBox() - this.minuteTextBox new
System.Windows.Forms.TextBox() - this.secondTextBox new
System.Windows.Forms.TextBox() - this.hourButton new System.Windows.Form
s.Button() - this.minuteButton new
System.Windows.Forms.Button() - this.secondButton new
System.Windows.Forms.Button() - this.addButton new System.Windows.Forms
.Button() - this.displayLabel1 new
System.Windows.Forms.Label() - this.displayLabel2 new
System.Windows.Forms.Label() - this.SuspendLayout()
- //
- // hourLabel
this.secondLabel.Location new
System.Drawing.Point(8, 74)
this.secondLabel.Name "secondLabel"
this.secondLabel.Size new System.Drawing.Size(72
, 16) this.secondLabel.TabIndex 2
this.secondLabel.Text "Second"
// // hourTextBox //
this.hourTextBox.Location new
System.Drawing.Point(64, 8)
this.hourTextBox.Name "hourTextBox"
this.hourTextBox.Size new System.Drawing.Size(32
, 20) this.hourTextBox.TabIndex 3
this.hourTextBox.Text "" //
// minuteTextBox //
this.minuteTextBox.Location new
System.Drawing.Point(64, 41)
this.minuteTextBox.Name "minuteTextBox"
this.minuteTextBox.Size new
System.Drawing.Size(32, 20)
this.minuteTextBox.TabIndex 4
this.minuteTextBox.Text "" //
// secondTextBox //
this.secondTextBox.Location new
System.Drawing.Point(64, 72)
this.secondTextBox.Name "secondTextBox"
this.secondTextBox.Size new
System.Drawing.Size(32, 20)
this.secondTextBox.TabIndex 5
this.secondTextBox.Text "" //
// hourButton //
16Using Properties Optional
- this.hourButton.Location new System.Drawing.Poin
t(104, 7) - this.hourButton.Name "hourButton"
- this.hourButton.Size new
System.Drawing.Size(96, 23) - this.hourButton.TabIndex 6
- this.hourButton.Text "Set Hour"
- this.hourButton.Click new
System.EventHandler(this.hourButton_Click) - //
- // minuteButton
- //
- this.minuteButton.Location new
System.Drawing.Point(104, 40) - this.minuteButton.Name "minuteButton"
- this.minuteButton.Size new
System.Drawing.Size(96, 23) - this.minuteButton.TabIndex 7
- this.minuteButton.Text "Set Minute"
- this.minuteButton.Click new
System.EventHandler(this.minuteButton_Click) - //
- // secondButton
- //
- this.secondButton.Location new
System.Drawing.Point(104, 71)
this.addButton.Text "Add 1 to Second"
this.addButton.Click new System.EventHandler(th
is.addButton_Click) // //
displayLabel1 //
this.displayLabel1.Location new
System.Drawing.Point(224, 39)
this.displayLabel1.Name "displayLabel1"
this.displayLabel1.Size new
System.Drawing.Size(176, 23)
this.displayLabel1.TabIndex 10 //
// displayLabel2 //
this.displayLabel2.Location new
System.Drawing.Point(224, 71)
this.displayLabel2.Name "displayLabel2"
this.displayLabel2.Size new
System.Drawing.Size(176, 33)
this.displayLabel2.TabIndex 11 //
// TimeTest3 //
this.AutoScaleBaseSize new System.Drawing.Size(5
, 13) this.ClientSize new
System.Drawing.Size(408, 133)
this.Controls.AddRange(new System.Windows.Forms.Co
ntrol
this.displayLabel2,
this.displayLabel1,
this.addButton,
this.secondButton,
this.minuteButton,
this.hourButton,
this.secondTextBox,
this.minuteTextBox,
this.hourTextBox,
this.secondLabel,
this.minuteLabel,
this.hourLabel)
17Using Properties Optional
- this.Name "TimeTest3"
- this.Text "Using Properties"
- this.ResumeLayout(false)
-
- endregion
- // main entry point for application
- STAThread
- static void Main()
-
- Application.Run( new TimeTest3() )
-
- // update display labels
- public void UpdateDisplay()
-
- displayLabel1.Text "Hour "
time.Hour - " Minute " time.Minute
// set Minute property when minuteButton pressed
private void minuteButton_Click(
object sender, System.EventArgs e )
time.Minute Int32.Parse( minuteTextBox.Text
) minuteTextBox.Text ""
UpdateDisplay() // set
Second property when secondButton pressed
private void secondButton_Click( object
sender, System.EventArgs e )
time.Second Int32.Parse( secondTextBox.Text )
secondTextBox.Text ""
UpdateDisplay() // add one
to Second when addButton pressed private
void addButton_Click( object sender,
System.EventArgs e ) time.Second
( time.Second 1 ) 60 if (
time.Second 0 )
time.Minute ( time.Minute 1 ) 60
if ( time.Minute 0 )
time.Hour ( time.Hour 1 ) 24
UpdateDisplay() // end method
addButton_Click // end class TimeTest3
18(No Transcript)
19Class Composition
- In many situations, referencing existing objects
is more convenient than rewriting the objects
code for new classes in new projects. - Suppose you want to implement an Alarm-Clock
object that needs to know when to sound the
alarm. Referencing an existing an existing Time
object is easier than rewriting a new Time
object. - The use of references to objects of preexisting
classes as members of new objects called
composition or aggregation. - Source files used for this discussion
- Date.cs
- Employee.cs
20Class Composition
- / Date class definition encapsulates month, day
and year. - using System
- namespace CompositionTest
-
- // Date class definition
- public class Date Object
-
- private int month // 1-12
- private int day // 1-31 based on month
- private int year // any year
- // 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
// 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 //
check if day in range for month if (
testDay gt 0 testDay lt daysPerMonth month
) return testDay //
check for leap year if ( month 2
testDay 29 ( year 400 0
( year 4 0 year 100
! 0 ) ) ) return testDay
Console.WriteLine( "Day 0
invalid. Set to day 1.", testDay )
return 1 // leave object in consistent state
// return date string as
month/day/year public string
ToDateString() return month
"/" day "/" year // end
class Date
21Class Composition
- // last name, birth date and hire date.
- using System
- namespace CompositionTest
-
- // Employee class definition
- public class Employee Object
-
- private string firstName
- private string lastName
- private Date birthDate // reference to a
Date object - private Date hireDate // reference to a
Date object - // 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
) -
// convert Employee to String
format public string ToEmployeeString()
return lastName ", " firstName
" Hired " hireDate.ToDateString(
) " Birthday "
birthDate.ToDateString() // end
class Employee
22Class Composition
- using System
- using System.Windows.Forms
- namespace CompositionTest
-
- // Composition class definition
- class CompositionTest
-
- // main entry point for application
- static void Main( string args )
-
- Employee e
- new Employee( "Bob", "Jones", 7, 24,
1949, 3, 12, 1988 ) - MessageBox.Show( e.ToEmployeeString(),
- "Testing Class Employee" )
-
- // end method Main
23Homework Assignment Paper Pencil Only due
next class.
- Create a class called Complex for performing
arithmetic with complex numbers. Write a driver
program to test your class. Complex numbers have
the form - realPart imaginaryPart i, where i is the
square root of -1. Use floating point variables
to represent the private data of the class.
Provide a constructor that enables an object of
this class to be initialized when it is declared.
Provide a no-argument constructor with default
values in case no initializers are provided.
Provide public methods for each of the following - Addition of two Complex numbers. The real parts
are added together and the imaginary parts are
added together. - Subtraction of two Complex numbers. The real part
of the right operand is subtracted from the real
part of the left operand and the imaginary part
of the right operand is subtracted from the
imaginary part of the left operand. - Printing of Complex numbers in the form (a,b),
where a is the real part and b is the imaginary
part.