module07: Arrays - Kasetsart University

Download Report

Transcript module07: Arrays - Kasetsart University

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
2
Arrays Revisited


Group multiple items of the same type into
one "variable" or "object"
Make programming easier to manage
a2=10
a1=3

a0=7
:
a5=17
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

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

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

A mechanism that bundles multiple items
of varying types into one item or "object"
Object studentInfo
Advisor="Arthur"
Dept="ME"
ID=48500000
Name="Paula"
ID:
Name:
Dept:
Advisor:
48500000
Paula
ME
Arthur
6
Encapsulation in C#

C# provides two kinds of data
encapsulation: struct and class


Objects created from a class can store a
fixed number of items


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 StudentInfo {
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)

Where do we put the class definition?



Inside or outside a class
Outside a method
E.g.,
using System;
using System;
class Test {
class StdInfo {
public int id;
public string name;
public string dept;
}
class StdInfo {
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

Syntax:
or

class-name obj-name;
obj-name = new class-name();
class-name obj-name = new class-name();
Example:
using System;
class Test {
class StdInfo {
public int id;
public string name;
public string dept;
}
public static void Main() {
StdInfo student = new StdInfo();
:
}
}
11
Object Creation Process
StdInfo student;
student = new StdInfo();
just a reference,
not an actual object
student
??
Object studentInfo
ID: ?
Name: ?
Dept: ?
Advisor: ?
Computer Memory
12
Accessing Object's Members

Syntax:
obj-name.member-name

Example:
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);
}
}
13
Array of Objects


Array of integers
7
3
10
5
8
17
5
8
17
7
3
0
1
2
3
4
5
6
7
8
9
10 11
Object of type StdInfo (with reference variable)
ID: 49051234
Name: Paula
Dept: ME
obj-var

10
Array of (references to) objects of type StdInfo
ID: 49051234
Name: Paula
Dept: ME
0
1
2
ID: 49052345
Name: Lisa
Dept: EE
ID: 49053456
Name: Uma
Dept: CPE
14
Creating Array of Objects

Syntax:
class-name[] array-name = new class-name[size];

Example:
using System;
class Test {
class StdInfo {
Create an array for
public int id;
storing 50 references to
public string name;
StdInfo objects
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 actual object
StdInfo for each
reference in the array
}
}
15
Accessing Objects in Array

Syntax:
array-name[index].member

Example:

Set Student#2's name to "Ariya"
students[2].name = "Ariya";

Display Student#3's department
Console.WriteLine("Department: {0}", students[3].dept);
16
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";
}
0
1
2
3
ID:
Name:
Dept:
49051234
Paula
ENVE
ID:
Name:
Dept:
49052345
Lisa
ME
ID:
Name:
Dept:
49053456
Uma
Ariya
CPE
ID:
Name:
Dept:
49054567
Masha
EE
17
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;
}
18
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;
}
19
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);
}
20
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]);
}
}
21
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)
22
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
Class Circle
Properties: radius, color
circle2
color = Red
radius = 1.5
objects
of class
Circle
circle3
color = Blue
radius = 2
23
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
24
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
25
Example: Member Methods

Consider the following Person class
class Person {
public string name;
public int
birth_year;
}

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!
public int GetAge() {
return 2010 – birth_year;
}
}
26
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()
{
:
}
}
27
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);
28
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);
29
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
30
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;
}
}
31
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);
}
32
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
v = (vx,vy)
(x,y)
+
a = (ax,ay)
(0,0)
+
v = (vx,vy)
33
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 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/s2)
class Ball {
public double sx, sy;
public double vx, vy;
public double ax, ay;
}
34
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
{
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 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;
}
}
36
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);
}
37
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
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.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);
Enter initial vx: 50
Enter initial vy: 50
b.Update(1);
Time
sx
sy
vx
vy
}
---------------------------------0
0.00
0.00
50.00
50.00
Console.ReadLine();
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
50.00
50.00
50.00
50.00
50.00
50.00
50.00
20.60
10.80
1.00
-8.80
-18.60
-28.40
-38.20
-48.00
39
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

40
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
41
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
42