Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming (part 1 – Data Encapsulation)

Similar presentations


Presentation on theme: "Object-Oriented Programming (part 1 – Data Encapsulation)"— Presentation transcript:

1 Object-Oriented Programming (part 1 – Data Encapsulation)
INF230 Basics in C# Programming AUBG, COS dept Lecture 21 Title: Object-Oriented Programming (part 1 – Data Encapsulation) Reference: Doyle, chap 4

2 Lecture Contents: Components of a class
Methods and properties used for object-oriented development Constructors Own instance methods mutators/accessors Call instance methods including mutators and accessors

3 Chapter 4 Creating Your Own Classes C# Programming:
From Problem Analysis to Program Design 4th Edition

4 Informal introduction to concept of classes/objects
Transition From Structured Programming to OOP From Think in Functions to Think in Objects From Algorithms + Data Structures = Programs To Classes + Objects = Programs

5 Formal introduction to concept of classes/objects
OOP (Object Oriented Programming): Data Encapsulation & Data Hiding Inheritance Polymorphism

6 3 main OOP characteristics
Data Encapsulation/Data Hiding Data and its routines /named methods/ are said to be encapsulated into a single entity. Data is concealed within a class, so that it cannot be accessed mistakenly from methods outside the class. Inheritance Polymorphism

7 3 main OOP characteristics
Data Encapsulation and Data Hiding Inheritance The process of creating new classes, called derived classes from existing classes or base classes Polymorphism

8 3 main OOP characteristics
Data Encapsulation and Data Hiding Inheritance Polymorphism Generally, the ability to appear in many forms, or in other words Giving different meanings to the same thing More specifically, in OOP it is the ability to redefine methods for derived classes

9 3 main OOP characteristics
Data Encapsulation and Data Hiding Inheritance Polymorphism And many other, e.g. Abstract classes Interfaces

10 The Object Concept Solution is defined in terms of a collection of cooperating objects Class serves as template from which many objects can be created Abstraction Attributes (data) Behaviors (processes on the data) C# Programming: From Problem Analysis to Program Design

11 Class SmallObj - definition
{ private int somedata; public int getSomeData() { return somedata; } public void setSomeData(int d) { somedata = d; } public void ShowData() Console.WriteLine("\n\nData is = {0}", somedata); } } // end of class

12 Class SmallObj – how to use?
static void Main(string[] args) { SmallObj a = new SmallObj(); a.setSomeData(713); Console.WriteLine(" {0}", a.getSomeData() ); a.ShowData(); . . . Console.ReadKey(); }

13 Anatomy of a Class Class components: Member data /fields/ Methods
Constructors Accessors / Mutators In stance Methods and Class Methods Properties Events

14 Private Member Data All code you write is placed in a class
When you define a class, you declare instance variables or fields that represent state of an object Fields are declared inside the class, but not inside any specific method Fields become visible to all members of the class, including all of the methods Data members are defined to have private access C# Programming: From Problem Analysis to Program Design

15 Private Member Data (continued)
public class Student { private int studentNumber; private string studentFirstName; private string studentLastName; private int score1; private int score2; private int score3; private string major; … C# Programming: From Problem Analysis to Program Design

16 Private Member Data (continued)
public class CarpetCalculator { private double pricePerSqYard; private double noOfSqYards; … C# Programming: From Problem Analysis to Program Design

17 Anatomy of a Class Class components Methods: Constructors

18 Constructor Special type of method used to create objects
Create instances of class Instantiate the class Constructors differ from other methods Constructors do not return a value Also do not include keyword void Constructors use same identifier (name) as class Constructors use public access modifiers C# Programming: From Problem Analysis to Program Design

19 Constructor (cont.) Do not use static keyword
Static associated with class method Constructor – special type of instance method Do not return a value void is not included Same identifier as the class name Overloaded Default constructor No arguments Write one constructor and you lose the default one C# Programming: From Problem Analysis to Program Design

20 Constructor (continued)
public access modifier is always associated with constructors //Default constructor public Student ( ) { } //Constructor with one parameter public Student (int sID ) studentNumber = sID; C# Programming: From Problem Analysis to Program Design

21 Constructor (continued)
//Constructor with three parameters public Student (string sID, string firstName, string lastName) { studentNumber = sID; studentFirstName = firstName; studentLastName = lastName; } Design classes to be as flexible and as full-featured as possible Include multiple constructors C# Programming: From Problem Analysis to Program Design

22 Writing Your Own Instance Methods
In addition to Constructors Accessors Mutators Other methods to perform behaviors of the class C# Programming: From Problem Analysis to Program Design

23 Accessors Getters Returns the current value
Standard naming convention → prefix with “Get” Accessor for noOfSquareYards public double GetNoOfSqYards( ) { return noOfSqYards; } Properties serve purpose Accessor C# Programming: From Problem Analysis to Program Design

24 Mutators Setters Normally includes one parameter
Method body → single assignment statement Standard naming convention → prefix with ”Set” Can be overloaded C# Programming: From Problem Analysis to Program Design

25 Mutator Examples Overloaded Mutator
public double SetNoOfSqYards(double squareYards) { noOfSquareYards = squareYards; } public void SetNoOfSquareYards(double length, double width) // length, width – in feet; 1 yard = 3 feet; 1 sq.yard = 9 sq.feer noOfSquareYards = length * width / 9; Overloaded Mutator C# Programming: From Problem Analysis to Program Design

26 Other Instance Methods
No need to pass arguments to these methods – Defined in the same class as the data members Instance methods can directly access private data members Define methods as opposed to storing values that are calculated from other private data members public double CalculateAverage( ) { return (score1 + score2 + score3) / 3.0; } C# Programming: From Problem Analysis to Program Design

27 Anatomy of a Class Class components: Properties

28 Property Can replace accessors and mutators
Properties look like a data field More closely aligned to methods Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character Doesn’t have to be the same name – no syntax error will be thrown C# Programming: From Problem Analysis to Program Design

29 Property public double NoOfSqYards { get return noOfSqYards; } set
// given data member noOfSqYards. See the property NoOfSqYards below: public double NoOfSqYards { get return noOfSqYards; } set noOfSqYards = value; C# Programming: From Problem Analysis to Program Design

30 Property (continued) If an instantiated object is named berber, to change the NoOfSqYards, write: berber.NoOfSqYards = 45.60; C# Programming: From Problem Analysis to Program Design

31 Property (continued) If an instantiated object is named berber, to get value of data member associated to /i.e. hidden behind/ the property NoOfSqYards, write: double var; var = berber.NoOfSqYards; Console.WriteLine(“{0}”, berber.NoOfSqYards); C# Programming: From Problem Analysis to Program Design

32 Property (continued) Given a class Employee and data member salary
private decimal salary; See the property Salary below: If an instantiated object is named peter, to update /i.e. modify – increase or decrease/ value of data member salary associated to /i.e. hidden behind/ the property Salary, write: peter.Salary = peter.Salary M; peter.Salary -= M; C# Programming: From Problem Analysis to Program Design

33 Anatomy of a Class Class components:
Inheritance relation and access to base class methods

34 ToString( ) Method All user-defined classes inherit four methods from the object class ToString( ) Equals( ) GetType( ) GetHashCode( ) C# Programming: From Problem Analysis to Program Design

35 ToString( ) Method ToString( ) method is called automatically by several methods Write( ) WriteLine( ) methods Can also invoke or call the ToString( ) method directly C# Programming: From Problem Analysis to Program Design

36 ToString( ) Method (continued)
Returns a human-readable string Can write a new definition for the ToString( ) method to include useful details public override string ToString( ) { // return string value } Keyword override added to provide new implementation details Always override the ToString( ) method This enables you to decide what should be displayed if the object is printed C# Programming: From Problem Analysis to Program Design

37 ToString( ) Example public override string ToString( ) { return "Price Per Square Yard: " + pricePerSqYard.ToString("C") + "\nTotal Square Yards needed: " + noOfSqYards.ToString("F1") + "\nTotal Price: " + DetermineTotalCost( ).ToString("C"); } C# Programming: From Problem Analysis to Program Design

38 ToString( ) method Sometimes useful to add format specifiers as one of the arguments to the Write( ) and WriteLine( ) methods – Invoke ToString( ) Numeric data types such as int, double, float, and decimal data types have overloaded ToString( ) methods pricePerSqYard.ToString("C") C# Programming: From Problem Analysis to Program Design

39 Anatomy of a Class Calling methods

40 Calling Instance Methods
Instance methods are nonstatic method Call nonstatic methods with objects – not classes Static calls to members of Math and Console classes answer = Math.Pow(4, 2) Console.WriteLine( ) If you need to invoke the method inside the class it is defined in, simply use method name If you need to invoke the method outside the class it is defined in, precede method name with object identifier berber.GetNoOfSquareYards( ) C# Programming: From Problem Analysis to Program Design

41 Calling the Constructor
Normally first method called Creates an object instance of the class ClassName objectName = new ClassName(argumentList); or ClassName objectName; objectName = new ClassName(argumentList); Keyword new used as operator to call constructor methods CarpetCalculator plush = new CarpetCalculator ( ); CarpetCalculator pile = new CarpetCalculator(37.90,17.95); C# Programming: From Problem Analysis to Program Design

42 Constructor (continued)
Default values are assigned to variables of the value types when no arguments are sent to constructor C# Programming: From Problem Analysis to Program Design

43 Calling the Constructor Method
Figure 4-4 Intellisense displays available constructors C# Programming: From Problem Analysis to Program Design

44 Using Public Members Figure 4-5 Public members of the Student class
C# Programming: From Problem Analysis to Program Design

45 Calling Accessor and Mutator Methods
Method name is preceded by the object name Calling mutator method berber.SetNoOfSquareYards(27.83); Calling accessor method Console.WriteLine("{0:N2}", berber.GetNoOfSquareYards( )); C# Programming: From Problem Analysis to Program Design

46 Using property instead of mutator methods
Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); If property defined, can use property instead of mutator methods PropertyName = value; // Acts like mutator here NoOfSquareYards = 27.83; C# Programming: From Problem Analysis to Program Design

47 Using property instead of accessor methods
Method name is preceded by the object name Console.WriteLine("{0:N2}", berber.GetNoOfSquareYards( )); If property defined, can use property instead of accessor methods Console.WriteLine("{0:N2}", berber.NoOfSquareYards); // Property Acts like accessor here C# Programming: From Problem Analysis to Program Design

48 Calling Other Instance Methods
Call must match method signature If method returns a value, must be a place for a value to be returned Student aStudentObject = new Student("1234", "Maria", "Smith", 97, 75, 87, "CS"); average = aStudentObject.CalculateAverage( ); No arguments needed as parameters to the CalculateAverage( ) method. CalculateAverage( ) is a member of the Student class and has full access to all Student members. C# Programming: From Problem Analysis to Program Design

49 Testing Your New Class Different class is needed for testing and using your class Test class has Main( ) in it Construct objects of your class Use the properties to assign and retrieve values Invoke instance methods using the objects you construct C# Programming: From Problem Analysis to Program Design

50 User classes and Test class
using System; namespace MyUserClasses { public class Student } //===================================== namespace TestUserClasses using MyUserClasses; class Test public static void Main()

51 Test Class With multiclass solutions all input and output should be included in the class that has the Main( ) method Eventual goal will be to place your class files, like Student and CarpetCalculator, in a library so that the classes can be used by different applications Some of these applications might be Windows applications; some may be console applications; others may be Web application Do not include ReadLine( ) or WriteLine( ) in your class methods C# Programming: From Problem Analysis to Program Design

52 Testing Your New Class Figure 4-7 Output from Carpet example using
instance methods C# Programming: From Problem Analysis to Program Design

53 How to create a class By hand – typing all the source text concerning the class template – as it was done with SmallObj class Using a number of tools available in Visual Studio to aid in the development of applications To add a second class in your application, use the PROJECT menu or Solution Explorer window

54 Add a Class Use the PROJECT menu or the Solution Explorer Window
Select your project file, then Right-mouse click and select the option Add, Class Solution Explorer Window enables you to create a class diagram C# Programming: From Problem Analysis to Program Design

55 Open the Class Diagram from Solution Explorer, View Class Diagram
Figure 4-1 Student class diagram created in Visual Studio C# Programming: From Problem Analysis to Program Design

56 Class Diagram (continued)
After the class diagram is created, add the names of data members or fields and methods using the Class Details section Right click on class diagram to open Class Details window Figure 4-2 Student class diagram details C# Programming: From Problem Analysis to Program Design

57 Class Diagram (continued)
When you complete class details using the Class Diagram tool, code is automatically placed in the file. Figure 4-3 Auto generated code from Student class diagram C# Programming: From Problem Analysis to Program Design

58 Practical exercises .

59 Class SmallObj Modify the SmallObj class:
Ignore ShowData() method as unnecessary Define property SOMEDATA associated with somedata field Demonstrate how to use the property. SmallObj a = new SmallObj(); a.SOMEDATA = 5555; Console.WriteLine("\n\n\n{0}", a.SOMEDATA);

60 Class SparePart Develop a class with data members – fields:
int modelno, int partno, double cost And Constructors No arg, 3-arg Accessor/Mutator methods Properties Modelno Partno Cost

61 Class Counter Develop a class with data members – fields: int count
And Constructors No arg, 1-arg Accessor/Mutator methods Property Count

62 Class Distance Develop a class with data members – fields: int feet
double inches Constructors No arg, 1-arg (2 copies), 2-arg Accessor/Mutator methods Properties Feet Inches

63 Class Point Develop a class with data members – fields: int xcoord
int ycoord Constructors No arg, 2-arg Accessor/Mutator methods Properties Xcoord Ycoord

64 Class Circle Develop a class with data members – fields:
int xcoord int ycoord double radius Constructors No arg, 3-arg Accessor/Mutator methods Properties Xcoord Ycoord Radius

65 Thank You For Your Attention!

66 RealEstateInvestment Example
Figure 4-8 Problem specification for RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

67 Data for the RealEstateInvestment Example
Table 4-2 Instance variables for the RealEstateInvestment class C# Programming: From Problem Analysis to Program Design

68 Data for the RealEstateInvestment Example (continued)
Table 4-3 local variables for the property application class C# Programming: From Problem Analysis to Program Design

69 RealEstateInvestment Example (continued)
Figure 4-9 Prototype C# Programming: From Problem Analysis to Program Design

70 RealEstateInvestment Example (continued)
Figure Class diagrams C# Programming: From Problem Analysis to Program Design

71 RealEstateInvestment Example (continued)
Table 4-4 Properties for the RealEstateInvestment class C# Programming: From Problem Analysis to Program Design

72 RealEstateInvestment Example (continued)
Figure Structured English for the RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

73 Class Diagram Figure 4-12 RealEstateInvestment class diagram
C# Programming: From Problem Analysis to Program Design

74 Test and Debug Figure 4-13 Output from RealEstate Investment example
C# Programming: From Problem Analysis to Program Design


Download ppt "Object-Oriented Programming (part 1 – Data Encapsulation)"

Similar presentations


Ads by Google