Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Object-Oriented Program

Similar presentations


Presentation on theme: "C# Object-Oriented Program"— Presentation transcript:

1 C# Object-Oriented Program
Lecture 05 C# Object-Oriented Program Dr. Eng. Ibrahim El-Nahry

2 Learning Objectives Essentials of Object-Oriented Programming
Defining Object-Oriented Systems C# and Object Orientation C# Classes and Objects Using Encapsulation

3 Object – Oriented Programming
As hardware and software became increasingly complex, quality was often compromised. Researchers studied ways to maintain software quality and developed object-oriented programming in part to address common problems by strongly emphasizing discrete, reusable units of programming logic. The methodology focuses on data rather than processes, with programs composed of self-sufficient modules (objects) each containing all the information needed to manipulate its own data structure.

4 Object – Oriented Programming
The Object-Oriented methodology focuses on data rather than processes, with programs composed of self-sufficient modules (objects) each containing all the information needed to manipulate its own data structure. This is in contrast to the existing modular programming which had been dominant for many years that focused on the function of a module An object-oriented program may thus be viewed as a collection of cooperating objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform

5 OOP Fundamental Concepts
Fundamental Concepts in OOP are: Class Object Instance Method Abstraction Encapsulation Inheritance Polymorphism

6 OOP concepts : Objects An object is a unique programming entity that has attributes to describe it (like adjectives in grammar) and methods to retrieve/set attribute values (like verbs in grammar). Attributes Programmers store an object’s data in attributes, also called properties. Attributes provide us a way to describe an object, similar to adjectives in grammar. We can read property values or change properties, assigning values. Methods Whereas attributes describe an object, methods allow us to access object data. Methods are like verbs in grammar. We can manipulate object data, stored in attributes, using methods.

7 OOP concepts : Abstraction
One of the chief advantages of object-oriented programming is the idea that programmers can essentially focus on the “big picture” and ignore specific details regarding the inner-workings of an object. This concept is called abstraction. Events Object-oriented programming is inherently tied to user interaction. Programs record interaction in the form of events. Events are changes in an object’s environment to which it can react. Classes How do programmers get by implementing abstraction? They use a programming structure called a class. A class presents a blueprint of an object, its properties and its methods.

8 OOP concepts : Instantiation
To create an object based on a class, we create an instance of that class. This process is called instantiation. In C#, we use a special method called a constructor method to create an instance of an object. Encapsulation Abstraction in OOP is closely related to a concept called encapsulation. Data and the ways to get at that data are wrapped in a single package, a class. The only way to access such data is through that package. This idea translates to information hiding.

9 OOP concepts : Inheritance
Another of the main tenets of OOP is inheritance. Inheritance allows programmers to create new classes from existing ones. A child class inherits its properties and attributes from its parents, which programmers can change. Polymorphism Polymorphism describes how programmers write methods to do some general purpose function. Different objects might perform polymorphic methods differently.

10 C# Classes A C# class plays dual roles:
Program module: containing a list of (static) method declarations and (static) data fields Blueprint for generating objects It is the model or pattern from which objects are created Supports two techniques which are essence of object-oriented programming “data encapsulation” (for abstraction) “inheritance” (for code reuse)

11 User-Defined Class A user-defined class is also called a user-defined type class written by a programmer A class encapsulates (wrap together) data and methods: data members (member variables or instance variables) methods that manipulate data members

12 C# Objects An object has: state - descriptive characteristics
behaviors - what it can do (or be done to it) Note the interactions between state and behaviors the behavior of an object might change its state the behavior of an object might depend on its state

13 Defining Classes A class contains data declarations and method declarations public int x, y; private char ch; class MyClass Data declarations Method declarations Member (data/method) Access Modifiers public : member is accessible outside the class private : member is accessible only inside the class definition

14 Class membership Classes have member variables and methods
Class members are 1 of 3 types Public Private Protected

15 Public membership Everyone can access the member
The rest of the world The class itself Child classes You should avoid making member variables public, in order to prevent undesired modification

16 Private membership Only the class itself can access the member
It’s not visible to the rest of the world Child classes can’t access it either

17 Protected membership The middle ground between public and private
The outside world can’t access it… but derived classes can

18 Data Declarations Comparison: Local variables
You can define two types of variables in a class but not in any method (called class variables) static class variables nonstatic variables are called instance variables (fields) because each instance (object) of the class has its own copy class variables can be accessed in all methods of the class Comparison: Local variables Variables declared within a method or within a block statement Variables declared as local variables can only be accessed in the method or the block where they are declared

19 Method Declarations A class can define many types of methods, e.g.,
Access methods : read or display data Predicate methods : test the truth of conditions

20 Constructors 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) can take arguments Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values they do not return any value it has no return type, not even void Static classes can also have constructors

21 Destructor Destructors are used to destruct instances of classes.
Destructors are only used with classes. A class can only have one destructor. Destructors cannot be inherited or overloaded. Destructors cannot be called. They are invoked automatically. A destructor does not take modifiers or have parameters. The destructor implicitly calls Finalize on the base class of the object.

22 Example: Time1 class We define the Time1 class to represent time: midnight to 11:59:59 The state of a time object can be represented by: hour, minute, second: integers representing time We might define the following methods: a Time1 constructor, to set up the object a SetTime method, to set time a ToUniversalString method, to convert the internal representation to a string representing the time in 24 hour format a ToStandardString method, to convert the internal representation to a string representing the time in 12 hour format

23 1 // Time1.cs 2 // Class Time1 maintains time in 24-hour format. 3 4 using System; 5 6 // Time1 class definition 7 public class Time1 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // Time1 constructor initializes instance variables to // zero to set default time to midnight public Time1() { SetTime( 0, 0, 0 ); } 19 // 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 >= 0 && hourValue < 24 ) ? hourValue : 0; minute = ( minuteValue >= 0 && minuteValue < 60 ) ? minuteValue : 0; second = ( secondValue >= 0 && secondValue < 60 ) ? secondValue : 0; } 32 Default constructor Private instance variables Method SetTime Validate arguments

24 33 // convert time to universal-time (24 hour) format string
public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second ); } 39 // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } 47 48 } // end class Time1 Output time in universal format Output time in standard format

25 1 // TimeTest1.cs 2 // Demonstrating class Time1. 3 4 using System; 5 using System.Windows.Forms; 6 7 // TimeTest1 uses creates and uses a Time1 object 8 class TimeTest1 9 { // main entry point for application static void Main( string[] args ) { Time1 timeObj1 = new Time1(); // calls Time1 constructor string output; 15 // assign string representation of time to output output = "Initial universal time is: " + timeObj1.ToUniversalString() + "\nInitial standard time is: " + timeObj1.ToStandardString(); 21 // attempt valid time settings timeObj1.SetTime( 13, 27, 6 ); 24 // append new string representations of time to output output += "\n\nUniversal time after SetTime is: " + timeObj1.ToUniversalString() + "\nStandard time after SetTime is: " + timeObj1.ToStandardString(); 30 // attempt invalid time settings timeObj1.SetTime( 99, 99, 99 ); 33 Call default time constructor Call method SetTime to set the time with valid arguments Call method SetTime with invalid arguments

26 34 output += "\n\nAfter attempting invalid settings: " +
"\nUniversal time: " + time.ToUniversalString() + "\nStandard time: " + time.ToStandardString(); 37 MessageBox.Show( output, "Testing Class Time1" ); 39 } // end method Main 41 42 } // end class TimeTest1 Program Output

27 const 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

28 1 // 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 { // PI is constant variable public const double PI = ; 12 // radius is a constant variable // that is uninitialized public readonly int radius; 16 public Constants( int radiusValue ) { radius = radiusValue; } 21 22 } // end class Constants 23 24 // UsingConstAndReadOnly class definition 25 public class UsingConstAndReadOnly 26 { // method Main creates Constants // object and displays it's values static void Main( string[] args ) { Random random = new Random(); 32 Constants constantValues = new Constants( random.Next( 1, 20 ) ); 35 Constant variable PI Readonly variable radius; must be initialized in constructor Initialize readonly member radius

29 36 MessageBox.Show( "Radius = " + constantValues.radius +
"\nCircumference = " + * Constants.PI * constantValues.radius, "Circumference" ); 40 } // end method Main 42 43 } // end class UsingConstAndReadOnly Program Output

30 Using the this reference
Every object can reference itself by using the keyword this Often used to distinguish between a method’s variables and the instance variables of an object e.g., in constructors

31 1 // Time4.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time4 class definition 7 public class Time4 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // constructor public Time4( int hour, int minute, int second ) { this.hour = hour; this.minute = minute; this.second = second; } 20 // create string using this and implicit references public string BuildString() { return "this.ToStandardString(): " + this.ToStandardString() + "\nToStandardString(): " + ToStandardString(); } 28 The this reference is used to set the class member variables to the constructor arguments The this reference is used to refer to an instance method

32 29 // convert time to standard-time (12 hour) format string
public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( this.hour == 12 || this.hour == 0 ) ? 12 : this.hour % 12 ), this.minute, this.second, ( this.hour < 12 ? "AM" : "PM" ) ); } 37 38 } // end class Time4 The this reference is used to access member variables

33 1 // 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 { // main entry point for application static void Main( string[] args ) { Time4 time = new Time4( 12, 30, 19 ); 14 MessageBox.Show( time.BuildString(), "Demonstrating the \"this\" Reference" ); } 18 }

34 Encapsulation You can take one of two views of an object:
internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other part of the world

35 Encapsulation: An Object As a Black Box
From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object An encapsulated object can be thought of as a black box 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 Methods Client Data Can you think of another way to represent the state of an object of Time1?

36 Accomplish Encapsulation: Access Modifiers
In C#, we accomplish encapsulation through the appropriate use of access modifiers An access modifier is a C# keyword that specifies the accessibility of a method, data field, or class We will discuss two access modifiers: public, private We will discuss the other two modifiers (protected, internal) later For more details, please check C# programmer’s reference (linked on the lecture notes page)

37 The public and private Access Modifiers
Classes (types) and members of a class that are declared with public can be accessed from anywhere Members of a type that are declared with private can only be accessed from inside the class Members of a class declared without an access modifier have default private accessibility

38 1 // RestrictedAccess.cs
2 // Demonstrate compiler errors from attempt to access 3 // private class members. 4 5 class RestrictedAccess 6 { // main entry point for application static void Main( string[] args ) { Time1 time = new Time1(); 11 time.hour = 7; time.minute = 15; time.second = 30; } 16 17 } // end class RestrictedAccess RestrictedAccess Program Output Attempt to access private members

39 Using Access Modifiers to Implement Encapsulation: Data Fields
As a general rule, no object's data (state) should be declared with public accessibility How to internally represent the state of an object should be hidden from others Any changes to the object's state (its variables) should be accomplished by that object's methods We should make it difficult, if not impossible, for one object to "reach in" and directly alter another object's state

40 Implementing Data Encapsulation using Properties
Use C# properties to provide access to data safely data members should be declared private, with public properties that allow safe access to them You access the properties of a class as if you were accessing a data field ( i.e., no () ) Public properties allow clients to: Get (obtain the values of) private data get accessor: controls formatting and retrieval of data Set (assign values to) private data set accessor: ensure that the new value is appropriate for the data member

41 1 // Time3.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time3 class definition 7 public class Time3 8 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 12 // Time3 constructor initializes instance variables to // zero to set default time to midnight public Time3() { SetTime( 0, 0, 0 ); } 19 // Time3 constructor: hour supplied, minute and second // defaulted to 0 public Time3( int hour ) { SetTime( hour, 0, 0 ); } 26 // Time3 constructor: hour and minute supplied, second // defaulted to 0 public Time3( int hour, int minute ) { SetTime( hour, minute, 0 ); } 33

42 34 // Time3 constructor: hour, minute and second supplied
public Time3( int hour, int minute, int second ) { SetTime( hour, minute, second ); } 39 // Time3 constructor: initialize using another Time3 object public Time3( Time3 time ) { SetTime( time.Hour, time.Minute, time.Second ); } 45 // 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; Minute = minuteValue; Second = secondValue; } // property Hour public int Hour { get { return hour; } 63 set { hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); } } // end property Hour Property Hour Constructor that takes another Time3 object as an argument. New Time3 object is initialized with the values of the argument.

43 // property Minute public int Minute { get { return minute; } 78 set { minute = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 83 } // end property Minute 85 // property Second public int Second { get { return second; } 93 set { second = ( ( value >= 0 && value < 60 ) ? value : 0 ); } 98 } // end property Second 100 Property Minute Property Second

44 101 // convert time to universal-time (24 hour) format string
public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second ); } 107 // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( Hour == 12 || Hour == 0 ) ? 12 : Hour % 12 ), Minute, Second, ( Hour < 12 ? "AM" : "PM" ) ); } 115 116 } // end class Time3

45 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 { private System.Windows.Forms.Label hourLabel; private System.Windows.Forms.TextBox hourTextBox; private System.Windows.Forms.Button hourButton; 17 private System.Windows.Forms.Label minuteLabel; private System.Windows.Forms.TextBox minuteTextBox; private System.Windows.Forms.Button minuteButton; 21 private System.Windows.Forms.Label secondLabel; private System.Windows.Forms.TextBox secondTextBox; private System.Windows.Forms.Button secondButton; 25 private System.Windows.Forms.Button addButton; 27 private System.Windows.Forms.Label displayLabel1; private System.Windows.Forms.Label displayLabel2; 30 // required designer variable private System.ComponentModel.Container components = null; 33 private Time3 time; 35

46 public TimeTest3() { // Required for Windows Form Designer support InitializeComponent(); 40 time = new Time3(); UpdateDisplay(); } 44 // Visual Studio .NET generated code 46 // main entry point for application [STAThread] static void Main() { Application.Run( new TimeTest3() ); } 53 // update display labels public void UpdateDisplay() { displayLabel1.Text = "Hour: " + time.Hour + "; Minute: " + time.Minute + "; Second: " + time.Second; displayLabel2.Text = "Standard time: " + time.ToStandardString() + "\nUniversal time: " + time.ToUniversalString(); } 64

47 65 // set Hour property when hourButton pressed
private void hourButton_Click( object sender, System.EventArgs e ) { time.Hour = Int32.Parse( hourTextBox.Text ); hourTextBox.Text = ""; UpdateDisplay(); } 73 // set Minute property when minuteButton pressed private void minuteButton_Click( object sender, System.EventArgs e ) { time.Minute = Int32.Parse( minuteTextBox.Text ); minuteTextBox.Text = ""; UpdateDisplay(); } 82 // set Second property when secondButton pressed private void secondButton_Click( object sender, System.EventArgs e ) { time.Second = Int32.Parse( secondTextBox.Text ); secondTextBox.Text = ""; UpdateDisplay(); } 91 // add one to Second when addButton pressed private void addButton_Click( object sender, System.EventArgs e ) { 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

48 if ( time.Second == 0 ) { time.Minute = ( time.Minute + 1 ) % 60; 101 if ( time.Minute == 0 ) time.Hour = ( time.Hour + 1 ) % 24; } 105 UpdateDisplay(); } 108 109 } // end class TimeTest3 Program Output

49 Summary Programming objects are comprised of attributes and methods.
Classes provide programmers with blueprints of objects. To create an object from a class, we use constructor methods to create a class instance. Abstraction in OOP is closely related to a concept called encapsulation. Variables declared in a larger scope can be accessed in an enclosed scope, e.g. Variables declared in a class can be accessed by the methods in the class Variables declared in a method can only be accessed in the method Variables declared in a block can only be accessed in the block


Download ppt "C# Object-Oriented Program"

Similar presentations


Ads by Google