Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reference: COS240 Syllabus

Similar presentations


Presentation on theme: "Reference: COS240 Syllabus"— Presentation transcript:

1 Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 32 Title: C# Classes and Objects Reference: COS240 Syllabus 7/21/2018 Assoc. Prof. Stoyan Bonev

2 Lecture Contents: Structure of a C# program Components of a C# program
Accent on classes Components of a C# program Classes and Objects /Instances/ Methods constructors Methods getters Methods setters Properties Sample demo programs 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 2

3 Assoc. Prof. Stoyan Bonev
Anatomy of a C# program 7/21/2018 Assoc. Prof. Stoyan Bonev

4 The Basics of a C# Program
C# program: collection of classes. Classes capsulated as namespaces – named or unnamed Namespace: collection of related classes Class: collection of data items and methods Method: designed to accomplish a specific task There is a main method which provides the control of program flow in every C# program static void Main(string[] args) 7/21/2018 4 Assoc. Prof. Stoyan Bonev 4

5 C# Elements Figure 1-17 Relationship among C# elements 7/21/2018 5
Source: Longman dictionary 1987 Source: Longman dictionary 1987 5 5

6 Anatomy of a Class Classes defined inside namespaces Classes group:
Data members Member functions /methods/ All programs consist of at least one class that includes at least one method Main() Every class is named 7/21/2018 6 6 Source: Longman dictionary 1987 Source: Longman dictionary 1987 6 6

7 Assoc. Prof. Stoyan Bonev
Class Definition Building block of object-oriented program. The class is one of the two basic encapsulation constructs in C# (the other being the struct). Every executable statement must be placed inside a class or struct. Classes define a category, or type, of object. Classes define reference types that are the basic building blocks of C# programs, and they serve as ADT to create objects in OOP 7/21/2018 C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 7 7 Source: Longman dictionary 1987 Source: Longman dictionary 1987 7 7

8 Assoc. Prof. Stoyan Bonev
/* SquareExample.cs Author: Doyle */ using System; namespace Square { public class SquareExample public static void Main( ) int aValue = 768; int result; result = aValue * aValue; Console.WriteLine(“{0} squared is {1}”, aValue, result); Console.Read( ); } 7/21/2018 C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 8 8 Source: Longman dictionary 1987 Source: Longman dictionary 1987 8 8

9 Classes Declaration Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. using System; public class House { ... } public class Program public static void Main() int bedrooms = 3; 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 9

10 Class Definition (continued)
Define class members within curly braces Include data members Stores values associated with the state of the class Include method members Performs some behavior of the class Classes and class members need to be prefixed with visibility modifiers. See next two slides. 7/21/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 10 Source: Longman dictionary 1987 10

11 Prefixed Visibility modifiers for class members:
By default, if you declare a member variable (or anything else) in a class but do not specify its access level, the member is considered private and cannot be accessed from outside, that is by a non-member of that class. Therefore, to make a member accessible by other classes, you must declare it as public. You can use a mix of public and private members in a class and there is no (syntactic) rule on which access level should be listed first or last. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 11

12 Prefixed Visibility modifiers for classes:
abstract: An instance of the class cannot be created. Usually this means the class is intended to serve as a base class. sealed: The class cannot serve as a base class for another class (it can not be derived from). A class cannot be both abstract and sealed. internal: The class is only accessible from other classes in the same assembly. This is the default access for non-nested types. If no modifier is specified, the class has internal access. new: Used only with nested classes. new indicates that the class hides an inherited member of the same name. private: A nested class that can only be accessed inside the class in which it is defined. public: Instances of this class are available to any class that wants to access it. 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 12

13 Variables of a class type are created with the new operator
using System; public class House { ... } public class Program public static void Main() House property = new House(); 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 13

14 Contents of Classes class class_name { ... fields, constants...
... methods... ... constructors, destructors... ... properties... ... events... ... indexers... ... overloaded operators... ... nested types (classes, interfaces, structs, enums, delegates)... } 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 14

15 Constructors Destructors public MyClass(arguments){} ~MyClass(){}
Every class has a constructor, which is called automatically any time an instance of a class is created. The purpose of constructors is to initialize class members when the class is created. Constructors do not have return values and always have the same name as the class. If a class does not define any constructors, an implicit parameterless constructor is created. Constructors Destructors public MyClass(arguments){} ~MyClass(){} Classes can have multiple constructors, as long as the argument list is different. Destructors are never called directly, but instead called by the garbage collector. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 15

16 public OutputClass(string inputString) myString = inputString; }
using System; class OutputClass { string myString; // Constructor public OutputClass(string inputString) myString = inputString; } // Destructor ~OutputClass() // Some resource cleanup routines // Instance Method public void printString() Console.WriteLine(myString); Continued … 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 16

17 // Main begins program execution. public static void Main()
// Program start class class ExampleClass { // Main begins program execution. public static void Main() // Instance of OutputClass OutputClass outCl = new OutputClass("This is printed by the output class."); // Call OutputClass method outCl.printString(); } 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 17

18 A class can be created inside of another class.
A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside: public class Outside { public class Inside ... } A private nested class can only be accessed from within the block of its outer class. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 18

19 Methods (already discussed in previous lecture)
C#, organizes code in terms of functions. C# functions are member functions or methods of a class. Methods can take any number of parameters, or no parameters. Methods can return any type or void to indicate no return type. Parameters passed by value. Parameters passed by reference – ref, out keywords Parameters passed using params keyword. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 19

20 Access modifier – see next page
C# - Basics: Methods [access modifier][static][method modifier][return type] MethodName(formal parameters) { // method body ... } Access modifier – see next page The keyword static when used in a method header enables us to use methods of the class without instantiating any objects first. Method modifier – see next page + 1 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 20

21 Method Access Modifiers
public indicates the method is freely accessible inside and outside of the class in which it is defined. internal means the method is only accessible to types defined in the same assembly. protected means the method is accessible in the type in which it is defined, and in derived types of that type. This is used to give derived classes access to the methods in their base class. protected internal means the method is accessible to types defined in the same assembly or to types in a derived assembly. private methods are only accessible in the class in which they are defined. If no modifier is specified, the method is given private access. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 21

22 Method Modifiers virtual methods can be overriden by a derived class using the override keyword. abstract methods must be overriden in a derived class. If any method of a class is abstract, the entire class must be declared as abstract. sealed methods are methods that override an inherited virtual method having the same signature. When a method is sealed, it cannot be overriden in a derived class. 7/21/2018 7/21/2018 Assoc. Prof. Stoyan Bonev Assoc. Prof. Stoyan Bonev 22

23 Creating Your Own Classes
4 C# Programming: From Problem Analysis to Program Design 3rd Edition C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 23 Source: Longman dictionary 1987 23

24 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 C# Programming: From Problem Analysis to Program Design 24 Source: Longman dictionary 1987 24

25 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 C# Programming: From Problem Analysis to Program Design 25

26 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

27 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(); }

28 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

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

30 Add a Class Use the Project menu or the Solution Explorer Window
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 C# Programming: From Problem Analysis to Program Design 30

31 Class Diagram Figure 4-1 Student class diagram created in Visual Studio C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 31

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

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

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

35 Writing Your Own Instance Methods
Do not use static keyword Static – class method Constructor Do not return a value void is not included Same identifier as the class name Overloaded methods Default constructor No arguments Write one constructor and you lose the default one C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 35 Source: Longman dictionary 1987 35

36 Constructor 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 C# Programming: From Problem Analysis to Program Design 36

37 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 C# Programming: From Problem Analysis to Program Design 37 Source: Longman dictionary 1987 37

38 Accessor Getters Returns the current value
Standard naming convention → prefix with “Get” or “get” Accessor for noOfSquareYards is double GetNoOfSquareYards( ) { return …; } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 38 Source: Longman dictionary 1987 38

39 Mutators Setters Normally includes one parameter
Method body → single assignment statement Standard naming convention → prefix with ”Set” or “set” Mutator for noOfSquareYards is void SetNoOfSquareYards(double prm) { … = prm; } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 39

40 Mutator Examples 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

41 Accessor and Mutator Examples
public double getNoOfSquareYards( ) { return noOfSquareYards; } public void setNoOfSquareYards(double squareYards) noOfSquareYards = squareYards; Accessor Mutator C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 41 Source: Longman dictionary 1987 41

42 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

43 Property Can replace accessors and mutators
Properties looks 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

44 Property // 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

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

46 ToString( ) Method All user-defined classes inherit four methods from the object class ToString( ) Equals( ) GetType( ) GetHashCode( ) 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 C# Programming: From Problem Analysis to Program Design 46 Source: Longman dictionary 1987 46

47 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 C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 47 Source: Longman dictionary 1987 47

48 Creating objects /instances/

49 Calling Instance Methods – Constructor
Calling the constructor 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); CarpetCalculator berber = new CarpetCalculator (17.95); C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 49 Source: Longman dictionary 1987 49

50 Calling Accessor and Mutator Methods
Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); Console.WriteLine(“{0:N2}”,berber.GetNoOfSquareYards( )); Using properties PropertyName = value; and Console.Write(“Total Cost at {0:C} ”, berber.Price); C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 50 Source: Longman dictionary 1987 50

51 Calling Other Instance Methods
Call must match method signature If method returns a value, must be place for a value to be returned C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 51 Source: Longman dictionary 1987 51

52 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 C# Programming: From Problem Analysis to Program Design 52

53 Practical Tasks Demo program ObsoleteObjectProg1.cs
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 53 Source: Longman dictionary 1987 53

54 Practical Tasks namespace ObsoleteObjectProg1 { class ObsoleteObject private int x; // constructors public ObsoleteObject() { x = 0; } public ObsoleteObject(int par) { x = par; } // obsolete metod showData() public void showData() { Console.WriteLine("Data = " + x); } // obsolete metod getData() public void getData() Console.Write("Enter value for data member x = "); x = Convert.ToInt32(Console.ReadLine()); } } // end of class ObsoleteObject class Program static void Main(string[] args) ObsoleteObject a = new ObsoleteObject(); ObsoleteObject b = new ObsoleteObject(15); ObsoleteObject c = new ObsoleteObject(); a.showData(); b.showData(); c.getData(); c.showData(); C# Programming: From Problem Analysis to Program Design 54 Source: Longman dictionary 1987 54

55 Practical Tasks Demo program ModernObjectProg1GetterSetter.cs
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 55 Source: Longman dictionary 1987 55

56 Practical Tasks class ModernObject { private int x; // constructors
public ModernObject() { x = 0; } public ModernObject(int par) { x = par; } // method accessor public int getX() { return x; } // methods mutators public void setX(int par) { x = par; } public void setX(int par1, int par2) { x = par1 + par2; } public void setX(int par1, int par2, int par3) { x = par1 + par2 + par3; } } // end of class ModernObject C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 56 Source: Longman dictionary 1987 56

57 Practical Tasks class Program { static void Main(string[] args)
ModernObject a = new ModernObject(); ModernObject b = new ModernObject(15); ModernObject c = new ModernObject(); ModernObject d = new ModernObject(); ModernObject e = new ModernObject(); // test accessor and mutators methods c.setX(20); Console.WriteLine(" {0}", c.getX()); c.setX(20, 50); Console.WriteLine(" " + c.getX()); c.setX(20, 30, 40); Console.WriteLine(" " + c.getX()); ModernObject f = new ModernObject(115); Console.WriteLine(" " + f.getX()); f.setX(125); Console.WriteLine(" " + f.getX()); } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 57 Source: Longman dictionary 1987 57

58 Practical Tasks Demo program ModernObjectProg1GetterSetterProperty.cs
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 58 Source: Longman dictionary 1987 58

59 Practical Tasks namespace ModernObjectprog1 { class ModernObject
private int x; // constructors public ModernObject() { x = 0; } public ModernObject(int par) { x = par; } // property public int PropertyX get return x; } set x = value; } // end of property } // end of class ModernObject C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 59 Source: Longman dictionary 1987 59

60 Practical Tasks class Program { static void Main(string[] args)
ModernObject a = new ModernObject(); ModernObject b = new ModernObject(15); ModernObject c = new ModernObject(); ModernObject d = new ModernObject(); ModernObject e = new ModernObject(); // test get property Console.WriteLine(" " + f.PropertyX); // test set property and get property f.PropertyX = 135; Console.WriteLine(" " + f.PropertyX); } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 60 Source: Longman dictionary 1987 60

61 Practical session Reminder: Program Methods1.cs includes class Program with methods Main() and gcdr() namespace Methods1 { class Program static void Main(string[] args) … gcdr(a, b)); } static int gcdr(int m, int n) } // end of class Program } // end of namespace C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 61 61

62 Practical session Reorganize Methods1.cs program to Methods2.cs like this: the same method gcdr() appears in three classes namespace Methods2 { class Program Method static void Main() { … } Method static int gcdr() { … } } class Arithmetic1 Method public static int gcdr() { … } class Arithmetic2 Method public int gcdr() { … } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 62 62

63 Practical session Analyze the syntax correctness of the Main() method static void Main(string[] args) { int a, b; Arithmetic2 ar = new Arithmetic2(); Program pr = new Program(); a = 24; b = 15; Console.WriteLine("\n“+Program.gcdr(a, b)+" "+gcdr(a, b)); Console.WriteLine("\n“+pr.gcdr(a, b)); a = 20; b = 15; Console.WriteLine("\n\n" + Arithmetic1.gcdr(a, b)); a = 17; b = 15; Console.WriteLine("\n\n" + ar.gcdr(a, b)); } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 63 63

64 Practical session – digression on Java
Java provides no restriction as C#, no source in red static void main(String[] args) { int a, b; Arithmetic2 ar = new Arithmetic2(); Program pr = new Program(); a = 24; b = 15; System.out.print(" "+Program.gcdr(a, b)+" "+gcdr(a, b)); System.out.print(" "+pr.gcdr(a, b)); a = 20; b = 15; System.out.print(" " + Arithmetic1.gcdr(a, b)); a = 17; b = 15; System.out.print(" " + ar.gcdr(a, b)); } C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 64 64

65 Practical session Expand the reorganized program Methods2.cs adding more methods that reside in the same class with method Main() and in classes Arithmetic1 and Arithmetic2: Iterative GCD – gcdi() Iterative/Recursive factorial – facti(), factr() Iterative/Recursive Fibonacci – fiboi(), fibor() Iterative/Recursive Sum(1..n) – sumi(), sumr() Iterative/Recursive Power operator simulator – powi(), powr() C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 65 65

66 Practical Tasks Develop class Counter Data field: count Constructors
Getter method Setter method Property Method: incCount C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 66 Source: Longman dictionary 1987 66

67 Practical Tasks Develop class Distance Data fields: feet, inches
Constructors Getter methods Setter methods Properties C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 67 Source: Longman dictionary 1987 67

68 Practical exercises .

69 Class SmallObj Modify the SmallObj class:
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);

70 Class SparePart Develop a class with data members – fields:
int modelno, int partno, double cost And methods void SetPart(int mn, int pn, double cs) { modelno = mn; partno = pn; cost = cs; } void ShowPart() Console.WriteLne(…..);

71 Class SparePart modify the SparePart class introducing
getters /accessors/ setters /mutators/ properties For each one of the fields /data members/

72 Thank You for Your attention!


Download ppt "Reference: COS240 Syllabus"

Similar presentations


Ads by Google