1 / 42

Classes and Object-Oriented Programming in C#

Classes and Object-Oriented Programming in C#. Computers and Programming (01204111). Outline. Array revisited Data encapsulation in C# Class and object creation Array of objects Member methods Constructors. Array a. a0=7. :. a2=10. 7. 3. 10. 5. 8. 17. a5=17. 0. 1. 2. 3. 4.

eolande
Télécharger la présentation

Classes and Object-Oriented Programming in C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. Example • 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]; : } }

  5. More Example • 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...

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

  7. Encapsulation in C# • 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 • may be of different types • A class is defined by programmer

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

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

  10. Defining Class (cont'd) • Where do we put the class definition? • Inside or outside a class • Outside a method • E.g., 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() { : } } or

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

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

  13. Accessing Object's Members • Syntax: • 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); } }

  14. 7 3 10 5 8 17 5 8 17 7 3 10 0 1 2 3 4 5 6 7 8 9 10 11 ID: 49051234 obj-var Name: Paula Dept: ME ID: 49051234 ID: 49052345 ID: 49053456 Name: Paula Name: Lisa Name: Uma Dept: ME Dept: EE Dept: CPE 0 1 2 Array of Objects • Array of integers • Object of type StdInfo (with reference variable) • Array of (references to) objects of type StdInfo

  15. Creating Array of Objects • Syntax: • 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(); : } } Create an array for storing 50 references to StdInfo objects Create an actual object StdInfo for each reference in the array

  16. Accessing Objects in Array • Syntax: • 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. 0 ID: 49051234 1 Name: Paula Dept: ENVE 2 ID: 49052345 3 Name: Lisa Dept: ME ID: 49053456 Name: Uma Dept: CPE ID: 49054567 Name: Masha Dept: EE 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"; } Ariya

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

  19. ReadInfo Method • Reads all information for each student • 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; }

  20. ShowInfo Method • Takes a StdInfo and displays the information on screen • Returns nothing static void ShowInfo(StdInfo info) { Console.WriteLine("{0,3} {1,-10} {2,2}", info.id, info.name, info.score); }

  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]); } }

  22. Object-Oriented Programming • 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 • 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)

  23. Object-Oriented View of Classes • 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 circle1 color = Yellow radius = 1 create circle2 color = Red radius = 1.5 create objectsof classCircle Class Circle Properties: radius, color create circle3 color = Blue radius = 2

  24. OOP and Graphical User Interface • 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. Member 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

  26. Example: Member Methods • Consider the following Person class • We can add a GetAge 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! class Person { public string name; public int birth_year; public int GetAge() { return 2010 – birth_year; } }

  27. Thinking Corner • 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() { : } }

  28. Constructors • 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., class Person { public string name; public int birth_year; public Person() { birth_year = 1975; } } Person p = new Person(); Console.WriteLine(p.birth_year);

  29. Constructors with Parameters • 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.WriteLine(p.name); Console.WriteLine(p.birth_year);

  30. Referencing Members • 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

  31. Referencing Members: this Variable • 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; } }

  32. Thinking Corner • 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 c1 = new Circle(30); Circle c2 = new Circle(2.5); }

  33. a = (ax,ay) v = (vx,vy) v = (vx,vy) Example: Balls in 2D Space (1) • 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) 3 seconds passed (x,y) + (0,0) +

  34. Example: Balls in 2D Space (2) • 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/s2) class Ball { public double sx, sy; public double vx, vy; public double ax, ay; }

  35. Example: Balls in 2D Space (3) • 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; } }

  36. Example: Balls in 2D Space (4) • 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; } }

  37. Example: Balls in 2D Space (5) • Test the program • 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); }

  38. a = (0,-9.8) v = (50,50) Example: Projectile Motion (1) • 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

  39. Format the value to have 2 decimal places and width of 8 characters 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(); } Enter initial vx: 50 Enter initial vy: 50 Time sx sy vx vy ---------------------------------- 0 0.00 0.00 50.00 50.00 1 50.00 45.10 50.00 40.20 2 100.00 80.40 50.00 30.40 3 150.00 105.90 50.00 20.60 4 200.00 121.60 50.00 10.80 5 250.00 127.50 50.00 1.00 6 300.00 123.60 50.00 -8.80 7 350.00 109.90 50.00 -18.60 8 400.00 86.40 50.00 -28.40 9 450.00 53.10 50.00 -38.20 10 500.00 10.00 50.00 -48.00

  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 s 

  41. Challenging Corner • 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. Conclusion • 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

More Related