Classes and ObjectOriented Programming in C Computers and

Classes and Object-Oriented Programming in C# Computers and Programming (01204111)

Outline l l l Array revisited Data encapsulation in C# Class and object creation Array of objects Member methods Constructors 2

Arrays Revisited l l Group multiple items of the same type into one "variable" or "object" Make programming easier to manage a 0=7 a 2=10 : a 5=17 a 1=3 l Array a 7 3 10 5 8 17 0 1 2 3 4 5 What if we want to keep a few things that are of different types together? 3

Example l Imagine that you have to write a program Ø To store 100 students' names § Ø That's simple; just use an array . . . and their scores § Also simple; create another array using System; class Scoring { public static void Main() { string [] name = new string[100]; double [] score = new double[100]; : } } Ø . . . and also their ID, department, faculty, advisor, etc 4

More Example l From the previous slide: Ø Ø We want to store students' ID, name, score, department, faculty, advisor, etc We could write a program like this: using System; class Scoring { public static void Main() { string [] name = new string[100]; int [] ID = new int[100]; double [] score = new double[100]; string [] dept = new string[100]; string [] faculty = new string[100]; string [] advisor = new string[100]; : } } What a mess. . . 5

Data Encapsulation l A mechanism that bundles multiple items of varying types into one item or "object" Object student. Info Advisor="Arthur" Dept="ME" ID=48500000 Name="Paula" ID: Name: Dept: Advisor: 48500000 Paula ME Arthur 6

Encapsulation in C# l C# provides two kinds of data encapsulation: struct and class Ø l Objects created from a class can store a fixed number of items Ø l This course will focus on classes only may be of different types A class is defined by programmer 7

Using Class 1. Define a class 2. Create an object from the class 3. Access data in the object 8

Defining Class Must use "class" keyword Every class needs a name class Student. Info { public int id; public string name; public string dept; } Protection level – always use "public" for now Members (or properties) of objects to be created 9

Defining Class (cont'd( l Where do we put the class definition? Ø Ø l Inside or outside a class Outside a method E. g. , using System; class Test { class Std. Info { public int id; public string name; public string dept; } public static void Main() { : } } or class Test { public static void Main() { : } } 10

Creating Object from Class l Syntax: or l class-name obj-name; obj-name = new class-name(); class-name obj-name = new class-name(); Example: using System; class Test { class Std. Info { public int id; public string name; public string dept; } public static void Main() { Std. Info student = new Std. Info(); : } } 11

Object Creation Process Std. Info student; student = new Std. Info(); just a reference, not an actual object student ? ? Object student. Info ID: ? Name: ? Dept: ? Advisor: ? Computer Memory 12

Accessing Object's Members l Syntax: obj-name. member-name l Example: using System; class Test { class Std. Info { public int id; public string name; public string dept; } public static void Main() { Std. Info student = new Std. Info(); student. id = 49041234; student. name = "Paula"; student. dept = "ME"; Console. Write. Line("ID: {0}", student. id); } } 13

Array of Objects l l Array of integers 7 3 10 5 8 17 7 0 1 2 3 4 5 6 7 8 9 10 10 11 Object of type Std. Info (with reference variable) ID: Name: Dept: obj-var l 3 49051234 Paula ME Array of (references to) objects of type Std. Info ID: Name: Dept: 0 1 2 ID: Name: Dept: 49051234 Paula ME 49052345 Lisa EE ID: Name: Dept: 49053456 Uma CPE 14
![Creating Array of Objects l Syntax: class-name[] array-name = new class-name[size]; l Example: using Creating Array of Objects l Syntax: class-name[] array-name = new class-name[size]; l Example: using](http://slidetodoc.com/presentation_image_h2/77d750980f8aa004bd3ac4a9d47e52ab/image-15.jpg)
Creating Array of Objects l Syntax: class-name[] array-name = new class-name[size]; l Example: using System; class Test { class Std. Info { Create an array for public int id; storing 50 references to public string name; Std. Info objects public string dept; } public static void Main() { Std. Info [] students = new Std. Info[50]; for (int i = 0; i < 50; i++) students[i] = new Std. Info(); : Create an actual object Std. Info for each reference in the array } } 15
![Accessing Objects in Array l Syntax: array-name[index]. member l Example: Ø Set Student#2's name Accessing Objects in Array l Syntax: array-name[index]. member l Example: Ø Set Student#2's name](http://slidetodoc.com/presentation_image_h2/77d750980f8aa004bd3ac4a9d47e52ab/image-16.jpg)
Accessing Objects in Array l Syntax: array-name[index]. member l Example: Ø Set Student#2's name to "Ariya" students[2]. name = "Ariya"; Ø Display Student#3's department Console. Write. Line("Department: {0}", students[3]. dept); 16

Accessing Details class Std. Info { public int ID; public string Name; public string Dept; } static void Main() { Std. Info[] students; students = new Std. Info[4]; : : students[2]. Name = "Ariya"; } 0 1 2 3 ID: Name: Dept: 49051234 Paula ENVE ID: Name: Dept: 49052345 Lisa ME ID: Name: Dept: 49053456 Ariya Uma CPE ID: Name: Dept: 49054567 Masha EE 17

Example: Student Records l Get N students' information with 3 fields Ø ID, Name, Score l Then output a table of information l First, we define a class as shown: class Std. Info { public int id; public string name; public int score; } 18

Read. Info Method l l Reads all information for each student Returns an object of class Std. Info static Std. Info Read. Info() { Std. Info info = new Std. Info(); Console. Write("ID: "); info. id = int. Parse(Console. Read. Line()); Console. Write("Name: "); info. name = Console. Read. Line(); Console. Write("Score: "); info. score = int. Parse(Console. Read. Line()); return info; } 19

Show. Info Method l l Takes a Std. Info and displays the information on screen Returns nothing static void Show. Info(Std. Info info) { Console. Write. Line("{0, 3} {1, -10} {2, 2}", info. id, info. name, info. score); } 20

Put Them All Together using System; class Std. Records { // Define class Std. Info here // Define Read. Info() here // Define Show. Info() here static void Main() { Console. Write("How many students? "); int n = int. Parse(Console. Read. Line()); Std. Info[] students = new Std. Info[n]; for (int i = 0; i < n; i++) students[i] = Read. Info(); for (int i = 0; i < n; i++) Show. Info(students[i]); } } 21

Object-Oriented Programming l l Classes are more than just a mechanism to bundle data into objects Objects may have its own behaviors (defined by classes) to perform on its properties Ø Ø l E. g. , they know how to display their data on screen, or compute their properties E. g. , every circle object knows how to calculate its area These are the concepts of Object-Oriented Programming (OOP) 22

Object-Oriented View of Classes l A class serves like a template to create objects of the same type Ø A class defines a list of properties its objects must have, but does not specify the values of these properties at e e r c create Class Circle Properties: radius, color cre at e circle 1 color = Yellow radius = 1 circle 2 color = Red radius = 1. 5 objects of class Circle circle 3 color = Blue radius = 2 23

OOP and Graphical User Interface l GUI components we have seen are objects of some classes Ø E. g. , buttons are objects of class Button inside System. Windows. Forms namespace button 1. Left = 60 button 1. Top = 31 button 1. Height = 56 button 1. Width = 115 button 1. Text = "OK" button 2. Left = 144 button 2. Top = 127 button 2. Height = 75 button 2. Width = 23 button 2. Text = "Cancel" button 2. Color = Color. Red 24

Member Methods l Class may contain methods Ø Ø l Allow objects to perform computation on its own data Known as member methods Each member method can access other members inside the same object 25

Example: Member Methods l Consider the following Person class Person { public string name; public int birth_year; } l We can add a Get. Age method to the class to calculate a person’s age class Person { public string name; public int birth_year; In real program, 2010 should not be hard-coded like this! public int Get. Age() { return 2010 – birth_year; } } 26

Thinking Corner l Add two methods, Circumference and Area, into the Circle class below Ø So that each Circle object knows how to compute its own circumference length and area class Circle { public double radius; public double Circumference() { : } public double Area() { : } } 27

Constructors l A constructor is a special member method defined in a class Ø Ø l It allows us to specify how each object of this class gets constructed It’s a method with the same name as the class and without return type (not even void) E. g. , class Person { public string name; public int birth_year; public Person() { birth_year = 1975; } } Person p = new Person(); Console. Write. Line(p. birth_year); 28

Constructors with Parameters l l A constructor may also be defined to accept parameters E. g. , class Person { public string name; public int birth_year; public Person(string s) { name = s; birth_year = 1975; } } The new operation passes the parameter to the newly created object Person p = new Person("John"); Console. Write. Line(p. name); Console. Write. Line(p. birth_year); 29

Referencing Members l In the previous example, the parameter name s in the constructor is not so meaningful, so we change it to name class Person { public string name; public int birth_year; public Person(string name) { name = name; birth_year = 1975; } } Does nothing because both 'name's refer to the parameter of the constructor 30

Referencing Members: this Variable l To make a reference to the current object, the special keyword this can be used class Person { public string name; public int birth_year; public Person(string name) { this. name = name; this. birth_year = 1975; } } 31

Thinking Corner l Add a constructor to the Circle class so that its objects can be created with provided 'radius' parameter class Circle { public double radius; } static void Main() { Circle c 1 = new Circle(30); Circle c 2 = new Circle(2. 5); } 32

Example: Balls in 2 D Space (1( Let us write a program (OOP style) to simulate ball movement in 2 D space l Ø Ø Ø Each ball knows its own current acceleration and velocity (on both x- and y-axes) Each ball knows its current position (x, y) Each ball knows how to update its position and velocity after time t (seconds) has passed § Assuming constant acceleration (x, y) v = (vx, vy) 3 seconds passed (x, y) + a = (ax, ay) (0, 0) + v = (vx, vy) 33

Example: Balls in 2 D Space (2( l Let us define the class Ball so that each Ball object has the following properties: Ø Ø Ø double sx, sy – current position on the xand y- axes (in meters) double vx, vy – current velocity on the xand y- axes (in m/s) double ax, ay – current acceleration on the x- and y- axes (in m/s 2) class Ball { public double sx, sy; public double vx, vy; public double ax, ay; } 34

Example: Balls in 2 D Space (3( l Add a method Update to update the position and velocity of the ball Ø High school physics applies here class Ball { : public void { sx = sx + sy = sy + vx = vx + vy = vy + } } Update(double t) // t = time elapsed 0. 5*ax*t*t + vx*t; 0. 5*ay*t*t + vy*t; ax*t; ay*t; 35

Example: Balls in 2 D Space (4( l Finally, add a constructor to allow convenient creation of Ball objects class Ball { : public Ball(double sx, double sy, double vx, double vy, double ax, double ay) { this. sx = sx; this. sy = sy; this. vx = vx; this. vy = vy; this. ax = ax; this. ay = ay; } } 36

Example: Balls in 2 D Space (5( l l Test the program Simulate two Ball objects Ø Ø Ball b 1 moves at constant velocity (ax = ay = 0) Ball b 2 moves under Earth's gravity (ax = 0, ay = 9. 8) static void Main() { Ball b 1 = new Ball(0, 0, 10, 20, 0, 0); Ball b 2 = new Ball(0, 100, 0, -9. 8); b 1. Update(10); b 2. Update(10); Console. Write. Line("After 10 seconds…"); Console. Write("b 1 is at position ({0}, {1})", b 1. sx, b 1. sy); Console. Write. Line(" with velocity [{0} {1}]", b 1. vx, b 1. vy); Console. Write("b 1 is at position ({0}, {1})", b 2. sx, b 2. sy); Console. Write. Line(" with velocity [{0} {1}]", b 2. vx, b 2. vy); } 37

Example: Projectile Motion (1( l Simulate projectile motion on earth Ø Ø Ø Cannon ball exits the cannon at position (0, 0) Ask user for initial velocity Report the position of the cannon ball every second a = (0, -9. 8) v = (50, 50) 38

Example: Projectile Motion (2( static void Main() { Console. Write("Enter initial vx: "); double vx = double. Parse(Console. Read. Line()); Console. Write("Enter initial vy: "); double vy = double. Parse(Console. Read. Line()); Ball b = new Ball(0, 0, vx, vy, 0, -9. 8); Console. Write. Line("Time sx sy vx vy"); Console. Write. Line("-----------------"); for (int i = 0; i <= 10; i++) // simulate for 10 seconds { Console. Write. Line("{0, 2}{1, 8: f 2}{2, 8: f 2}{3, 8: f 2}{4, 8: f 2}", i, b. sx, b. sy, b. vx, b. vy); Enter initial vx: 50 Enter initial vy: 50 b. Update(1); Time sx sy vx vy } -----------------0 0. 00 50. 00 Console. Read. Line(); 1 50. 00 45. 10 50. 00 40. 20 2 100. 00 80. 40 50. 00 30. 40 } Format the value to have 2 decimal places and width of 8 characters 3 4 5 6 7 8 9 10 150. 00 200. 00 250. 00 300. 00 350. 00 400. 00 450. 00 500. 00 105. 90 121. 60 127. 50 123. 60 109. 90 86. 40 53. 10 10. 00 50. 00 20. 60 10. 80 1. 00 -8. 80 -18. 60 -28. 40 -38. 20 -48. 00 39

Thinking Corner l Modify the program in the previous example to ask user for starting speed angle of the cannon ball, instead of vx, vy s 40

Challenging Corner l Write a GUI application that creates several Ball objects, then simulates their movements and draw them on a window Ø Ø Use a Timer to update the time and draw the balls at new locations Make balls bounce when they hit walls 41

Conclusion l l Multiple related data items can be bundled into an object by defining a class for it Object-Oriented Programming (OOP) allows programmers to view data as objects that have their own behaviors 42
- Slides: 42