Download presentation
Presentation is loading. Please wait.
Published byLeona Heath Modified over 9 years ago
1
Classes and Object-Oriented Programming in C# Computers and Programming (01204111)
2
2 Outline Array revisited Array revisited Data encapsulation in C# Data encapsulation in C# Class and object creation Class and object creation Array of objects Array of objects Member methods Member methods Constructors Constructors
3
3 Arrays Revisited Group multiple items of the same type into one "variable" or "object" Group multiple items of the same type into one "variable" or "object" Make programming easier to manage Make programming easier to manage What if we want to keep a few things that are of different types together? What if we want to keep a few things that are of different types together? a1=3 a2=10 a0=7 a5=17 : 71035178 Array a 021354
4
4 Example Imagine that you have to write a program 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 ...and also their ID, department, faculty, advisor, etc using System; class Scoring { public static void Main() { string [] name = new string[100]; double [] score = new double[100]; : } using System; class Scoring { public static void Main() { string [] name = new string[100]; double [] score = new double[100]; : }
5
5 More Example From the previous slide: 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]; : } 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...
6
6 Data Encapsulation A mechanism that bundles multiple items of varying types into one item or "object" A mechanism that bundles multiple items of varying types into one item or "object" Dept="ME" Advisor="Arthur" Name="Paula" ID=48500000 48500000 Paula ME Arthur ID: Name: Dept: Advisor: Object studentInfo
7
7 Encapsulation in C# C# provides two kinds of data encapsulation: struct and class C# provides two kinds of data encapsulation: struct and class This course will focus on classes only Objects created from a class can store a fixed number of items Objects created from a class can store a fixed number of items may be of different types A class is defined by programmer A class is defined by programmer
8
8 Using Class 1.Define a class 2.Create an object from the class 3.Access data in the object
9
9 Defining Class class StudentInfo { public int id; public string name; public string dept; } class StudentInfo { public int id; public string name; public string dept; } Must use "class" keyword Every class needs a name Members (or properties) of objects to be created Protection level – always use "public" for now
10
10 Defining Class (cont'd) Where do we put the class definition? Where do we put the class definition? Inside or outside a class Outside a method E.g., E.g., using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { : } using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { : } using System; class StdInfo { public int id; public string name; public string dept; } class Test { public static void Main() { : } using System; class StdInfo { public int id; public string name; public string dept; } class Test { public static void Main() { : } or
11
11 Creating Object from Class Syntax: Syntax: or or Example: Example: class-name obj-name = new class-name(); using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo student = new StdInfo(); : } using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo student = new StdInfo(); : } class-name obj-name; obj-name = new class-name(); class-name obj-name; obj-name = new class-name();
12
12 Computer Memory Object Creation Process StdInfo student; student = new StdInfo(); StdInfo student; student = new StdInfo(); ?? just a reference, not an actual object ? ? ? ? ID: Name: Dept: Advisor: Object studentInfo student
13
13 Accessing Object's Members Syntax: Syntax: Example: Example: obj-name.member-name using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo student = new StdInfo(); student.id = 49041234; student.name = "Paula"; student.dept = "ME"; Console.WriteLine("ID: {0}", student.id); } using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo student = new StdInfo(); student.id = 49041234; student.name = "Paula"; student.dept = "ME"; Console.WriteLine("ID: {0}", student.id); }
14
14 Array of Objects Array of integers Array of integers Object of type StdInfo (with reference variable) Object of type StdInfo (with reference variable) Array of (references to) objects of type StdInfo Array of (references to) objects of type StdInfo 71035178 021354 51787103 68791110 49051234 Paula ME ID: Name: Dept: 49052345 Lisa EE ID: Name: Dept: 49053456 Uma CPE ID: Name: Dept: 012 49051234 Paula ME ID: Name: Dept: obj-var
15
15 Creating Array of Objects Syntax: Syntax: Example: Example: class-name[] array-name = new class-name[size]; using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo [] students = new StdInfo[50]; for (int i = 0; i < 50; i++) students[i] = new StdInfo(); : } using System; class Test { class StdInfo { public int id; public string name; public string dept; } public static void Main() { StdInfo [] students = new StdInfo[50]; for (int i = 0; i < 50; i++) students[i] = new StdInfo(); : } Create an array for storing 50 references to StdInfo objects Create an actual object StdInfo for each reference in the array
16
16 Accessing Objects in Array Syntax: Syntax: Example: Example: Set Student#2's name to "Ariya" Display Student#3's department array-name[index].member students[2].name = "Ariya"; Console.WriteLine("Department: {0}", students[3].dept);
17
17 Accessing Details class StdInfo { public int ID; public string Name; public string Dept; } static void Main() { StdInfo[] students; students = new StdInfo[4]; : students[2].Name = "Ariya"; } class StdInfo { public int ID; public string Name; public string Dept; } static void Main() { StdInfo[] students; students = new StdInfo[4]; : students[2].Name = "Ariya"; } 49051234 Paula ENVE ID: Name: Dept: 49052345 Lisa ME ID: Name: Dept: 49053456 Uma CPE ID: Name: Dept: 49054567 Masha EE ID: Name: Dept:01 2 3 Ariya
18
18 Example: Student Records Get N students' information with 3 fields Get N students' information with 3 fields ID, Name, Score Then output a table of information Then output a table of information First, we define a class as shown: First, we define a class as shown: class StdInfo { public int id; public string name; public int score; } class StdInfo { public int id; public string name; public int score; }
19
19 ReadInfo Method Reads all information for each student Reads all information for each student Returns an object of class StdInfo Returns an object of class StdInfo static StdInfo ReadInfo() { StdInfo info = new StdInfo(); Console.Write("ID: "); info.id = int.Parse(Console.ReadLine()); Console.Write("Name: "); info.name = Console.ReadLine(); Console.Write("Score: "); info.score = int.Parse(Console.ReadLine()); return info; } static StdInfo ReadInfo() { StdInfo info = new StdInfo(); Console.Write("ID: "); info.id = int.Parse(Console.ReadLine()); Console.Write("Name: "); info.name = Console.ReadLine(); Console.Write("Score: "); info.score = int.Parse(Console.ReadLine()); return info; }
20
20 ShowInfo Method Takes a StdInfo and displays the information on screen Takes a StdInfo and displays the information on screen Returns nothing Returns nothing static void ShowInfo(StdInfo info) { Console.WriteLine("{0,3} {1,-10} {2,2}", info.id, info.name, info.score); } static void ShowInfo(StdInfo info) { Console.WriteLine("{0,3} {1,-10} {2,2}", info.id, info.name, info.score); }
21
21 Put Them All Together using System; class StdRecords { // Define class StdInfo here // Define ReadInfo() here // Define ShowInfo() here static void Main() { Console.Write("How many students? "); int n = int.Parse(Console.ReadLine()); StdInfo[] students = new StdInfo[n]; for (int i = 0; i < n; i++) students[i] = ReadInfo(); for (int i = 0; i < n; i++) ShowInfo(students[i]); } using System; class StdRecords { // Define class StdInfo here // Define ReadInfo() here // Define ShowInfo() here static void Main() { Console.Write("How many students? "); int n = int.Parse(Console.ReadLine()); StdInfo[] students = new StdInfo[n]; for (int i = 0; i < n; i++) students[i] = ReadInfo(); for (int i = 0; i < n; i++) ShowInfo(students[i]); }
22
22 Object-Oriented Programming Classes are more than just a mechanism to bundle data into objects 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 Objects may have its own behaviors (defined by classes) to perform on its properties 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) These are the concepts of Object-Oriented Programming (OOP)
23
23 Object-Oriented View of Classes A class serves like a template to create objects of the same type 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 Class Circle Properties: radius, color create create create circle1 color = Yellow radius = 1 circle2 color = Red radius = 1.5 circle3 color = Blue radius = 2 objects of class Circle
24
24 OOP and Graphical User Interface GUI components we have seen are objects of some classes GUI components we have seen are objects of some classes E.g., buttons are objects of class Button inside System.Windows.Forms namespace button1.Left = 60 button1.Top = 31 button1.Height = 56 button1.Width = 115 button1.Text = "OK" button2.Left = 144 button2.Top = 127 button2.Height = 75 button2.Width = 23 button2.Text = "Cancel" button2.Color = Color.Red
25
25 Member Methods Class may contain methods Class may contain methods Allow objects to perform computation on its own data Known as member methods Each member method can access other members inside the same object Each member method can access other members inside the same object
26
26 Example: Member Methods Consider the following Person class Consider the following Person class We can add a GetAge method to the class to calculate a person’s age We can add a GetAge method to the class to calculate a person’s age class Person { public string name; public int birth_year; } class Person { public string name; public int birth_year; } class Person { public string name; public int birth_year; public int GetAge() { return 2010 – birth_year; } class Person { public string name; public int birth_year; public int GetAge() { return 2010 – birth_year; } In real program, 2010 should not be hard-coded like this!
27
27 Thinking Corner Add two methods, Circumference and Area, into the Circle class below 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() { : } class Circle { public double radius; public double Circumference() { : } public double Area() { : }
28
28 Constructors A constructor is a special member method defined in a class A constructor is a special member method defined in a class 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., E.g., class Person { public string name; public int birth_year; public Person() { birth_year = 1975; } class Person { public string name; public int birth_year; public Person() { birth_year = 1975; } Person p = new Person(); Console.WriteLine(p.birth_year); Person p = new Person(); Console.WriteLine(p.birth_year);
29
29 Constructors with Parameters A constructor may also be defined to accept parameters A constructor may also be defined to accept parameters E.g., E.g., class Person { public string name; public int birth_year; public Person(string s) { name = s; birth_year = 1975; } class Person { public string name; public int birth_year; public Person(string s) { name = s; birth_year = 1975; } Person p = new Person("John"); Console.WriteLine(p.name); Console.WriteLine(p.birth_year); Person p = new Person("John"); Console.WriteLine(p.name); Console.WriteLine(p.birth_year); The new operation passes the parameter to the newly created object
30
30 Referencing Members In the previous example, the parameter name s in the constructor is not so meaningful, so we change it to name 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; } 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
31
31 Referencing Members: this Variable To make a reference to the current object, the special keyword this can be used 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; } class Person { public string name; public int birth_year; public Person(string name) { this.name = name; this.birth_year = 1975; }
32
32 Thinking Corner Add a constructor to the Circle class so that its objects can be created with provided 'radius' parameter Add a constructor to the Circle class so that its objects can be created with provided 'radius' parameter class Circle { public double radius; } class Circle { public double radius; } static void Main() { Circle c1 = new Circle(30); Circle c2 = new Circle(2.5); } static void Main() { Circle c1 = new Circle(30); Circle c2 = new Circle(2.5); }
33
33 Example: Balls in 2D Space (1) Let us write a program (OOP style) to simulate ball movement in 2D space Let us write a program (OOP style) to simulate ball movement in 2D space 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) a = (ax,ay)(x,y) v = (vx,vy) 3 seconds passed (0,0) + +
34
34 Example: Balls in 2D Space (2) Let us define the class Ball so that each Ball object has the following properties: Let us define the class Ball so that each Ball object has the following properties: double sx,sy – current position on the x- and y- axes (in meters) double vx,vy – current velocity on the x- and 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; } class Ball { public double sx, sy; public double vx, vy; public double ax, ay; }
35
35 Example: Balls in 2D Space (3) Add a method Update to update the position and velocity of the ball Add a method Update to update the position and velocity of the ball High school physics applies here class Ball { : public void Update(double t) // t = time elapsed { sx = sx + 0.5*ax*t*t + vx*t; sy = sy + 0.5*ay*t*t + vy*t; vx = vx + ax*t; vy = vy + ay*t; } class Ball { : public void Update(double t) // t = time elapsed { sx = sx + 0.5*ax*t*t + vx*t; sy = sy + 0.5*ay*t*t + vy*t; vx = vx + ax*t; vy = vy + ay*t; }
36
36 Example: Balls in 2D Space (4) Finally, add a constructor to allow convenient creation of Ball objects 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; } 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; }
37
37 Example: Balls in 2D Space (5) Test the program Test the program Simulate two Ball objects Simulate two Ball objects Ball b1 moves at constant velocity (ax = ay = 0) Ball b2 moves under Earth's gravity (ax = 0, ay = 9.8) static void Main() { Ball b1 = new Ball(0,0,10,20,0,0); Ball b2 = new Ball(0,100,0,0,0,-9.8); b1.Update(10); b2.Update(10); Console.WriteLine("After 10 seconds…"); Console.Write("b1 is at position ({0},{1})", b1.sx, b1.sy); Console.WriteLine(" with velocity [{0} {1}]", b1.vx, b1.vy); Console.Write("b1 is at position ({0},{1})", b2.sx, b2.sy); Console.WriteLine(" with velocity [{0} {1}]", b2.vx, b2.vy); } static void Main() { Ball b1 = new Ball(0,0,10,20,0,0); Ball b2 = new Ball(0,100,0,0,0,-9.8); b1.Update(10); b2.Update(10); Console.WriteLine("After 10 seconds…"); Console.Write("b1 is at position ({0},{1})", b1.sx, b1.sy); Console.WriteLine(" with velocity [{0} {1}]", b1.vx, b1.vy); Console.Write("b1 is at position ({0},{1})", b2.sx, b2.sy); Console.WriteLine(" with velocity [{0} {1}]", b2.vx, b2.vy); }
38
38 Example: Projectile Motion (1) Simulate projectile motion on earth 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 v = (50,50) a = (0,-9.8)
39
39 Example: Projectile Motion (2) static void Main() { Console.Write("Enter initial vx: "); double vx = double.Parse(Console.ReadLine()); Console.Write("Enter initial vy: "); double vy = double.Parse(Console.ReadLine()); Ball b = new Ball(0, 0, vx, vy, 0, -9.8); Console.WriteLine("Time sx sy vx vy"); Console.WriteLine("----------------------------------"); for (int i = 0; i <= 10; i++) // simulate for 10 seconds { Console.WriteLine("{0,2}{1,8:f2}{2,8:f2}{3,8:f2}{4,8:f2}", i, b.sx, b.sy, b.vx, b.vy); b.Update(1); } Console.ReadLine(); } static void Main() { Console.Write("Enter initial vx: "); double vx = double.Parse(Console.ReadLine()); Console.Write("Enter initial vy: "); double vy = double.Parse(Console.ReadLine()); Ball b = new Ball(0, 0, vx, vy, 0, -9.8); Console.WriteLine("Time sx sy vx vy"); Console.WriteLine("----------------------------------"); for (int i = 0; i <= 10; i++) // simulate for 10 seconds { Console.WriteLine("{0,2}{1,8:f2}{2,8:f2}{3,8:f2}{4,8:f2}", i, b.sx, b.sy, b.vx, b.vy); b.Update(1); } Console.ReadLine(); } Enter initial vx: 50 Enter initial vy: 50 Time sx sy vx vy ---------------------------------- 0 0.00 0.00 50.00 50.00 0 0.00 0.00 50.00 50.00 1 50.00 45.10 50.00 40.20 1 50.00 45.10 50.00 40.20 2 100.00 80.40 50.00 30.40 2 100.00 80.40 50.00 30.40 3 150.00 105.90 50.00 20.60 3 150.00 105.90 50.00 20.60 4 200.00 121.60 50.00 10.80 4 200.00 121.60 50.00 10.80 5 250.00 127.50 50.00 1.00 5 250.00 127.50 50.00 1.00 6 300.00 123.60 50.00 -8.80 6 300.00 123.60 50.00 -8.80 7 350.00 109.90 50.00 -18.60 7 350.00 109.90 50.00 -18.60 8 400.00 86.40 50.00 -28.40 8 400.00 86.40 50.00 -28.40 9 450.00 53.10 50.00 -38.20 9 450.00 53.10 50.00 -38.20 10 500.00 10.00 50.00 -48.00 Format the value to have 2 decimal places and width of 8 characters
40
40 Thinking Corner Modify the program in the previous example to ask user for starting speed and angle of the cannon ball, instead of vx,vy Modify the program in the previous example to ask user for starting speed and angle of the cannon ball, instead of vx,vy s
41
41 Challenging Corner Write a GUI application that creates several Ball objects, then simulates their movements and draw them on a window 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
42
42 Conclusion Multiple related data items can be bundled into an object by defining a class for it 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 Object-Oriented Programming (OOP) allows programmers to view data as objects that have their own behaviors
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.