Classes and Object-Classes and Object-Oriented Programming in Oriented Programming in C#C#
Computers and ProgrammingComputers and Programming(01204111)(01204111)
2
OutlineOutline Array revisitedArray revisited Data encapsulation in C#Data encapsulation in C# Class and object creationClass and object creation Array of objectsArray of objects Member methodsMember methods ConstructorsConstructors
3
Arrays RevisitedArrays Revisited Group multiple items of the same Group multiple items of the same
type into one "type into one "variablevariable" or "" or "objectobject"" Make programming easier to Make programming easier to
managemanage
What if we want to keep a few things What if we want to keep a few things that are of different types together?that are of different types together?
a1=3a1=3
a2=10a2=10
a0=7a0=7
a5=17a5=17
:: 77 101033 55 171788Array Array aa
00 2211 33 5544
4
ExampleExample Imagine that you have to write a programImagine that you have to write a program
To store 100 students' namesTo store 100 students' names That's simple; just use an arrayThat's simple; just use an array
...and their scores...and their scores Also simple; create another arrayAlso simple; create another array
...and also their ...and also their IDID, , departmentdepartment, , facultyfaculty, , advisoradvisor, etc, 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
More ExampleMore Example From the previous slide:From the previous slide:
We want to store students' ID, name, We want to store students' ID, name, score, department, faculty, advisor, etcscore, department, faculty, advisor, etc
We could write a program like this: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 What a mess...mess...
6
Data EncapsulationData Encapsulation A mechanism that bundles multiple A mechanism that bundles multiple
items of varying types into one item items of varying types into one item or "or "objectobject""
Dept="ME"Dept="ME"
Advisor="Arthur"Advisor="Arthur"
Name="Paula"Name="Paula"ID=48500000ID=48500000
4850000048500000PaulaPaulaMEMEArthurArthur
ID:ID:Name:Name:Dept:Dept:
Advisor:Advisor:
Object Object studentInfostudentInfo
7
Encapsulation in C#Encapsulation in C# C# provides two kinds of data C# provides two kinds of data
encapsulation: encapsulation: structstruct and and classclass This course will focus on classes onlyThis course will focus on classes only
Objects created from a class can Objects created from a class can store a fixed number of itemsstore a fixed number of items may be of different typesmay be of different types
A A classclass is defined by programmer is defined by programmer
8
Using ClassUsing Class
1.Define a class1.Define a class1.Define a class1.Define a class
2.Create an object from the class2.Create an object from the class2.Create an object from the class2.Create an object from the class
3.Access data in the object3.Access data in the object3.Access data in the object3.Access data in the object
9
Defining ClassDefining 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 "Must use "classclass" " keywordkeyword
Every class Every class needs a needs a namename
MembersMembers (or (or propertiesproperties) )
of objects to be createdof objects to be createdProtection level – Protection level – always use "always use "publicpublic" "
for nowfor now
10
Defining Class (cont'd)Defining Class (cont'd) Where do we put the class Where do we put the class
definition?definition? Inside or outside a classInside or outside a class Outside a methodOutside 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() { : }}
oror
11
Creating Object from ClassCreating Object from Class Syntax:Syntax:
oror
Example:Example:
class-name obj-name = new class-name();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
Computer MemoryComputer Memory
Object Creation ProcessObject Creation Process
StdInfo student;
student = new StdInfo();
StdInfo student;
student = new StdInfo(); ????
just a reference, just a reference, not an actual objectnot an actual object
????????
ID:ID:Name:Name:Dept:Dept:
Advisor:Advisor:
Object Object studentInfostudentInfo
studentstudent
13
Accessing Object's Accessing Object's MembersMembers Syntax:Syntax:
Example:Example:
obj-name.member-nameobj-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
Array of ObjectsArray of Objects Array of integersArray of integers
Object of type StdInfo (with reference Object of type StdInfo (with reference variable)variable)
Array of (references to) objects of type Array of (references to) objects of type StdInfoStdInfo
77 101033 55 171788
00 2211 33 5544
55 171788 77 101033
66 8877 99 11111010
4905123449051234PaulaPaulaMEME
ID:ID:Name:Name:Dept:Dept:
4905234549052345LisaLisaEEEE
ID:ID:Name:Name:Dept:Dept:
4905345649053456UmaUmaCPECPE
ID:ID:Name:Name:Dept:Dept:
00 11 22
4905123449051234PaulaPaulaMEME
ID:ID:Name:Name:Dept:Dept:
obj-varobj-var
15
Creating Array of ObjectsCreating Array of Objects Syntax:Syntax:
Example:Example:
class-name[] array-name = new class-name[size];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 Create an array for storing 50 references storing 50 references
to StdInfo objectsto StdInfo objects
Create an actual object Create an actual object StdInfo for each StdInfo for each
reference in the arrayreference in the array
16
Accessing Objects in ArrayAccessing Objects in Array Syntax:Syntax:
Example:Example: Set Student#2's name to "Ariya"Set Student#2's name to "Ariya"
Display Student#3's departmentDisplay Student#3's department
array-name[index].memberarray-name[index].member
students[2].name = "Ariya";students[2].name = "Ariya";
Console.WriteLine("Department: {0}", students[3].dept);Console.WriteLine("Department: {0}", students[3].dept);
17
Accessing DetailsAccessing 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";}
4905123449051234PaulaPaulaENVEENVE
ID:ID:Name:Name:Dept:Dept:
4905234549052345LisaLisaMEME
ID:ID:Name:Name:Dept:Dept:
4905345649053456UmaUmaCPECPE
ID:ID:Name:Name:Dept:Dept:
4905456749054567MashaMashaEEEE
ID:ID:Name:Name:Dept:Dept:
00
11
22
33
AriyaAriya
18
Example: Example: Student RecordsStudent Records Get Get NN students' information with 3 fields students' information with 3 fields
ID, Name, ScoreID, Name, Score Then output a table of informationThen 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
ReadInfoReadInfo Method Method Reads all information for each Reads all information for each
studentstudent Returns an object of class StdInfoReturns 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
ShowInfoShowInfo Method Method Takes a StdInfo and displays the Takes a StdInfo and displays the
information on screeninformation on screen Returns nothingReturns 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
Put Them All TogetherPut Them All Togetherusing 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
Object-Oriented Object-Oriented ProgrammingProgramming Classes are more than just a Classes are more than just a
mechanism to bundle data into mechanism to bundle data into objectsobjects
Objects may have its own behaviors Objects may have its own behaviors (defined by classes) to perform on its (defined by classes) to perform on its propertiesproperties E.g., they know how to display their E.g., they know how to display their
data on screen, or compute their data on screen, or compute their propertiesproperties
E.g., every circle object knows how to E.g., every circle object knows how to calculate its areacalculate its area
These are the concepts of Object-These are the concepts of Object-Oriented Programming (OOP)Oriented Programming (OOP)
23
Object-Oriented View of Object-Oriented View of ClassesClasses A A classclass serves like a serves like a templatetemplate to to
create create objectsobjects of the same type of the same type A class defines a list of properties its A class defines a list of properties its
objects must have, but does not specify objects must have, but does not specify the values of these propertiesthe values of these properties
Class Circle Properties: radius, color
createcreate
create
create
createcreate
circle1 color = Yellow radius = 1
circle2 color = Red radius = 1.5
circle3 color = Blue radius = 2
objectsobjectsof classof classCircleCircle
24
OOP and Graphical User OOP and Graphical User InterfaceInterface GUI components we have seen are GUI components we have seen are
objects of some classesobjects of some classes E.g., buttons are objects of class E.g., buttons are objects of class ButtonButton
inside inside System.Windows.FormsSystem.Windows.Forms namespacenamespacebutton1.Left = 60button1.Top = 31button1.Height = 56button1.Width = 115button1.Text = "OK"
button2.Left = 144button2.Top = 127button2.Height = 75button2.Width = 23button2.Text = "Cancel"button2.Color = Color.Red
25
Member MethodsMember Methods Class may contain methodsClass may contain methods
Allow objects to perform computation Allow objects to perform computation on its own dataon its own data
Known as Known as member methodsmember methods Each member method can access Each member method can access
other members inside the same other members inside the same objectobject
26
Example: Example: Member Member MethodsMethods Consider the following Person classConsider the following Person class
We can add a GetAge method to the We can add a GetAge method to the class to calculate a person’s ageclass 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,In real program,2010 should not 2010 should not be hard-coded be hard-coded like this!like this!
27
Thinking CornerThinking Corner Add two methods, Add two methods, CircumferenceCircumference
and and AreaArea, into the Circle class below, into the Circle class below So that each Circle object knows how to So that each Circle object knows how to
compute its own circumference length compute its own circumference length and areaand area
class Circle{ public double radius;
public double Circumference() { : }
public double Area() { : }}
class Circle{ public double radius;
public double Circumference() { : }
public double Area() { : }}
28
ConstructorsConstructors A constructor is a special member method A constructor is a special member method
defined in a classdefined in a class It allows us to specify how each object of this It allows us to specify how each object of this
class gets constructedclass gets constructed It’s a method with the It’s a method with the same name as the classsame name as the class
and and without return typewithout return type (not even (not even voidvoid)) 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
Constructors with Constructors with ParametersParameters A constructor may also be defined to A constructor may also be defined to
accept parametersaccept 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 The new operation passes the parameter passes the parameter to the newly created to the newly created
objectobject
30
Referencing MembersReferencing Members In the previous example, the In the previous example, the
parameter name parameter name ss in the constructor in the constructor is not so meaningful, so we change it is not so meaningful, so we change it to to namename
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 Does nothing because both because both
'name's refer to the 'name's refer to the parameter of the parameter of the
constructorconstructor
31
Referencing Members: Referencing Members: thisthis VariableVariable To make a reference to the current To make a reference to the current
object, the special keyword object, the special keyword thisthis can can be usedbe 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
Thinking CornerThinking Corner Add a constructor to the Circle class Add a constructor to the Circle class
so that its objects can be created so that its objects can be created with provided with provided 'radius'radius' parameter' 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
Example: Balls in 2D Example: Balls in 2D Space (1)Space (1) Let us write a program (OOP style) to Let us write a program (OOP style) to
simulate ball movement in 2D spacesimulate ball movement in 2D space Each ball knows its own current Each ball knows its own current accelerationacceleration
and and velocityvelocity (on both x- and y-axes) (on both x- and y-axes) Each ball knows its current Each ball knows its current positionposition (x,y) (x,y) Each ball knows how to update its position Each ball knows how to update its position
and velocity after time and velocity after time tt (seconds) has passed (seconds) has passed Assuming constant accelerationAssuming constant acceleration
(x,y)(x,y)
v = (vx,vy)
a = (ax,ay)
(x,y)(x,y)
v = (vx,vy)
3 seconds 3 seconds passedpassed
(0,0)(0,0)
++
++
34
Example: Balls in 2D Example: Balls in 2D Space (2)Space (2) Let us define the class Let us define the class BallBall so that so that
each Ball object has the following each Ball object has the following properties:properties: double sx,sydouble sx,sy – current position on the – current position on the
x- and y- axes (in meters)x- and y- axes (in meters) double vx,vydouble vx,vy – current velocity on the – current velocity on the
x- and y- axes (in m/s)x- and y- axes (in m/s) double ax,aydouble ax,ay – current acceleration on – current acceleration on
the x- and y- axes (in m/sthe x- and y- axes (in m/s22))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
Example: Balls in 2D Example: Balls in 2D Space (3)Space (3) Add a method Update to update the Add a method Update to update the
position and velocity of the ballposition and velocity of the ball High school physics applies hereHigh 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
Example: Balls in 2D Example: Balls in 2D Space (4)Space (4) Finally, add a constructor to allow Finally, add a constructor to allow
convenient creation of Ball objectsconvenient 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
Example: Balls in 2D Example: Balls in 2D Space (5)Space (5) Test the programTest the program Simulate two Ball objectsSimulate two Ball objects
Ball b1 moves at constant velocity Ball b1 moves at constant velocity (ax = ay = 0)(ax = ay = 0)
Ball b2 moves under Earth's gravity Ball b2 moves under Earth's gravity (ax = 0, ay = 9.8)(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
Example: Projectile Motion Example: Projectile Motion (1)(1) Simulate projectile motion on earthSimulate projectile motion on earth
Cannon ball exits the cannon at Cannon ball exits the cannon at position (0,0)position (0,0)
Ask user for initial velocityAsk user for initial velocity Report the position of the cannon ball Report the position of the cannon ball
every secondevery second
v = (50,50)
a = (0,-9.8)
39
Example: Projectile Motion Example: Projectile Motion (2)(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: 50Enter initial vx: 50Enter initial vy: 50Enter initial vy: 50Time sx sy vx vyTime sx sy vx vy-------------------------------------------------------------------- 0 0.00 0.00 50.00 50.000 0.00 0.00 50.00 50.00 1 50.00 45.10 50.00 40.201 50.00 45.10 50.00 40.20 2 100.00 80.40 50.00 30.402 100.00 80.40 50.00 30.40 3 150.00 105.90 50.00 20.603 150.00 105.90 50.00 20.60 4 200.00 121.60 50.00 10.804 200.00 121.60 50.00 10.80 5 250.00 127.50 50.00 1.005 250.00 127.50 50.00 1.00 6 300.00 123.60 50.00 -8.806 300.00 123.60 50.00 -8.80 7 350.00 109.90 50.00 -18.607 350.00 109.90 50.00 -18.60 8 400.00 86.40 50.00 -28.408 400.00 86.40 50.00 -28.40 9 450.00 53.10 50.00 -38.209 450.00 53.10 50.00 -38.2010 500.00 10.00 50.00 -48.0010 500.00 10.00 50.00 -48.00
Format the value to have 2 decimal Format the value to have 2 decimal places and width of 8 charactersplaces and width of 8 characters
40
Thinking CornerThinking Corner Modify the program in the previous Modify the program in the previous
example to ask user for starting example to ask user for starting speed and angle of the cannon ball, speed and angle of the cannon ball, instead of vx,vyinstead of vx,vy
ss
41
Challenging CornerChallenging Corner Write a GUI application that creates Write a GUI application that creates
several Ball objects, then simulates their several Ball objects, then simulates their movements and draw them on a windowmovements and draw them on a window Use a Timer to update the time and draw the Use a Timer to update the time and draw the
balls at new locationsballs at new locations Make balls bounce when they hit wallsMake balls bounce when they hit walls
42
ConclusionConclusion Multiple related data items can be Multiple related data items can be
bundled into an object by defining a bundled into an object by defining a class for itclass for it
Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) allows programmers to view data as allows programmers to view data as objects that have their own objects that have their own behaviorsbehaviors