Encapsulation, Lecture Slide - Computer Science, Slides of C programming

Classes and objects, Defining classes, Method declarations, Encapsulation two view of an object, An objects as a black box, Access Modifiers, The public and private access modifiers, Implementing data encapsulation using properties, The effect of public and private accessibility

Typology: Slides

2010/2011

Uploaded on 10/05/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #17:
Encapsulation
http://flint.cs.yale.edu/cs112/
2
Outline
rAdmin. and review
rDefining good classes: the encapsulation
principle and C# language support
3
Recap: Classes and Objects
rA C# class plays dual roles:
mprogram module: containing a list of (static) method
declarations and (static) data fields
mblueprint for generating objects
supports two techniques which are essence of object-oriented
programming
data encapsulation” (for abstraction)
inheritance” (for code reuse)
rAn object has:
mstate -descriptive characteristics
data declarations
mbehaviors -what it can do (or be done to it)
methods declarations
4
public int x, y;
private char ch;
class MyClass
Defining Classes
Data member declarations
Data member declarations
Method member declarations
Method member declarations
member (data/method) access modifiers
public : member is accessible outside the class
private : member is accessible only inside the
class definition
5
Method Declarations
rAccess methods : read or display data
rPredicate methods : test the truth of conditions
rConstructors
initialize objects of the class
they have the same name as the class
There may be more than one constructor per class (overloaded constructors)
Even if the constructor does not explicitly initialize a data member, all data
members are initialized
»primitive numeric types are set to 0
»boolean types are set to false
»reference (class as type) types are set to null
If a class has no constructor, a default constructor is provided
»It has no code and takes no parameters
they do not return any value
it has no return type, not even void
Outline
Time2.cs
1 // Time2.cs
2 // Class Time2 provides overloaded constructors.
3
4 using System;
5
6 // Time2 class definition
7 public class Time2
8 {
9 private int hour; // 0-23
10 private int minute; // 0-59
11 private int second; // 0-59
12
13 // Time2 constructor initializes instance variables to
14 // zero to set default time to midnight
15 public Time2()
16 {
17 SetTime( 0, 0, 0);
18 }
19
20 // Time2 constructor: hour supplied, minute and second
21 // defaulted to 0
22 public Time2( int hour )
23 {
24 SetTime( hour, 0, 0);
25 }
26
27 // Time2 constructor: hour and minute supplied, second
28 // defaulted to 0
29 public Time2( int hour, int minute )
30 {
31 SetTime( hour, minute, 0 );
32 }
33-65 // lines 33-65 omitted
Default constructor
Constructor which takes
the hour as the input
Constructor which takes the hour
and minute as input
pf3
pf4
pf5

Partial preview of the text

Download Encapsulation, Lecture Slide - Computer Science and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #17:

Encapsulation

http://flint.cs.yale.edu/cs112/

Outline

r Admin. and review

r Defining good classes: the encapsulation

principle and C# language support

Recap: Classes and Objects

r A C# class plays dual roles:

m program module: containing a list of (static) method

declarations and (static) data fields

m blueprint for generating objects

  • supports two techniques which are essence of object-oriented

programming

  • data encapsulation ” (for abstraction)
  • inheritance ” (for code reuse)

r An object has:

m state - descriptive characteristics

  • data declarations

m behaviors - what it can do (or be done to it)

  • methods declarations

public int x, y;

private char ch;

class MyClass

Defining Classes

Data member declarations Data member declarations

Method member declarationsMethod member declarations

member (data/method) access modifiers

public : member is accessible outside the class

private : member is accessible only inside the

class definition

Method Declarations

r Access methods : read or display data

r Predicate methods : test the truth of conditions

r Constructors

  • initialize objects of the class
  • they have the same name as the class
    • There may be more than one constructor per class (overloaded constructors)
    • Even if the constructor does not explicitly initialize a data member, all data

members are initialized

» primitive numeric types are set to 0

» boolean types are set to false

» reference (class as type) types are set to null

  • If a class has no constructor, a default constructor is provided

» It has no code and takes no parameters

  • they do not return any value
    • it has no return type, not even void

Outline

Time2.cs

1 // Time2.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time2 class definition 7 public class Time 8 { 9 private int hour; // 0- 10 private int minute; // 0- 11 private int second; // 0- 12 13 // Time2 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time2() 16 { 17 SetTime( 0, 0, 0 ); 18 } 19 20 // Time2 constructor: hour supplied, minute and second 21 // defaulted to 0 22 public Time2( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 } 26 27 // Time2 constructor: hour and minute supplied, second 28 // defaulted to 0 29 public Time2( int hour, int minute ) 30 { 31 SetTime( hour, minute, 0 ); 32 } 33-65 // lines 33-65 omitted

Default constructor

Constructor which takes

the hour as the input

Constructor which takes the hour

and minute as input

Outline

Time2.cs

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

Outline

TimeTest2.cs

1 // TimeTest2.cs 2 // Using overloaded constructors. 3 4 using System; 5 using System.Windows.Forms; 6 7 // TimeTest2 demonstrates constructors of class Time 8 class TimeTest 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 Time2 time1, time2, time3, time4, time5, time6; 14 15 time1 = new Time2(); // 00:00: 16 time2 = new Time2( 2 ); // 02:00: 17 time3 = new Time2( 21, 34 ); // 21:34: 18 time4 = new Time2( 12, 25, 42 ); // 12:25: 19 time5 = new Time2( 27, 74, 99 ); // 00:00: 20 time6 = new Time2( time4 ); // 12:25: 21 22 String output = "Constructed with: " + 23 "\ntime1: all arguments defaulted" + 24 "\n\t" + time1.ToUniversalString() + 25 "\n\t" + time1.ToStandardString(); 26 27 output += "\ntime2: hour specified; minute and " + 28 "second defaulted" + 29 "\n\t" + time2.ToUniversalString() + 30 "\n\t" + time2.ToStandardString(); 31 32 output += "\ntime3: hour and minute specified; " + 33 "second defaulted" + 34 "\n\t" + time3.ToUniversalString() + 35 "\n\t" + time3.ToStandardString();

Test the constructors

Outline

TimeTest2.cs

Program Output

37 output += "\ntime4: hour, minute, and second specified" + 38 "\n\t" + time4.ToUniversalString() + 39 "\n\t" + time4.ToStandardString(); 40 41 output += "\ntime5: all invalid values specified" + 42 "\n\t" + time5.ToUniversalString() + 43 "\n\t" + time5.ToStandardString(); 44 45 output += "\ntime6: Time2 object time4 specified" + 46 "\n\t" + time6.ToUniversalString() + 47 "\n\t" + time6.ToStandardString(); 48 49 MessageBox.Show( output, 50 "Demonstrating Overloaded Constructors" ); 51 52 } // end method Main 53 54 } // end class TimeTest

Outline

r Admin. and review

ÿ Defining good classes: the encapsulation

principle and C# language support

Encapsulation: Two Views of an Object

r You can take one of two views of an object:

m internal - the structure of its data, the algorithms

used by its methods

m external - the interaction of the object with other

part of the world

Encapsulation: An Object As a Black Box

r From the external view, an object is an encapsulated entity,

providing a set of specific services

m These services define the interface to the object

m An encapsulated object can be thought of as a black box

m The user, or client , of an object can request its services, but it

should not have to be aware of how those services are

accomplished

ClientClient Methods

Data

Can you think of another way to

represent the state of an object of Time1?

Outline

Time3.cs

34 // Time3 constructor: hour, minute and second supplied 35 public Time3( int hour, int minute, int second ) 36 { 37 SetTime( hour, minute, second ); 38 } 39 40 // Time3 constructor: initialize using another Time3 object 41 public Time3( Time3 time ) 42 { 43 SetTime( time.Hour, time.Minute, time.Second ); 44 } 45 46 // 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; 52 Minute = minuteValue; 53 Second = secondValue; 54 } 56 // property Hour 57 public int Hour 58 { 59 get 60 { 61 return hour; 62 } 63 64 set 65 { 66 hour = ( ( value >= 0 && value < 24 )? value : 0 ); 67 } 68 } // end property Hour

Constructor that takes another

Time3 object as an argument. New

Time3 object is initialized with the

values of the argument.

Property Hour

Outline

Time3.cs

71 // property Minute 72 public int Minute 73 { 74 get 75 { 76 return minute; 77 } 78 79 set 80 { 81 minute = ( ( value >= 0 && value < 60 )? value : 0 ); 82 } 83 84 } // end property Minute 85 86 // property Second 87 public int Second 88 { 89 get 90 { 91 return second; 92 } 93 94 set 95 { 96 second = ( ( value >= 0 && value < 60 )? value : 0 ); 97 } 98 99 } // end property Second 100

Property Minute

Property Second

Outline

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 } 107 108 // 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 } 115 116 } // end class Time

Outline

TimeTest3.cs

1 // TimeTest3.cs 2 // Demonstrating Time3 properties Hour, Minute and Second. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // TimeTest3 class definition 12 public class TimeTest3 : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Label hourLabel; 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 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 variable 32 private System.ComponentModel.Container components = null; 33 34 private Time3 time; 35

Outline

TimeTest3.cs

36 public TimeTest3() 37 { 38 // Required for Windows Form Designer support 39 InitializeComponent(); 40 41 time = new Time3(); 42 UpdateDisplay(); 43 } 44 45 // Visual Studio .NET generated code 46 47 // main entry point for application 48 [STAThread] 49 static void Main() 50 { 51 Application.Run( new TimeTest3() ); 52 } 53 54 // 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

Outline

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 } 73 74 // 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 } 82 83 // 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 } 91 92 // 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

Outline

TimeTest3.cs

Program Output

98 if ( time.Second == 0 ) 99 { 100 time.Minute = ( time.Minute + 1 ) % 60; 101 102 if ( time.Minute == 0 ) 103 time.Hour = ( time.Hour + 1 ) % 24; 104 } 105 106 UpdateDisplay(); 107 } 108 109 } // end class TimeTest

Using Access Modifiers to Implement

Encapsulation: Methods

r Public methods present to the class’s clients a view of

the services that the class provides

  • public methods are also called service methods

r A method created simply to assist service

methods is called a support or helper method

  • since a support method is not intended to be called by a

client, it should not be declared with public accessibility

The Effects of Public and Private Accessibility

violate Encapsulation

Unless properties

enforce

encapsulation

provide services

to clients

support other

methods in the

class

public private

variables

methods

Example: a different

implementation of Time