Lecture 26

advertisement
Lecture 26



Log into Windows/ACENET. Use a web
browser to download today's exercise program,
PointClassDemo.zip.
Browse to PointClassDemo.zip and extract the
project folder. Double-click into the project
folders to the solution file, then double-click it
to start up VS.
Questions?
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
1
Outline

GUI notes

ListBoxes

Abstract data types (ADTs)

Classes – Chapter 4

Attributes

Constructors

Instance methods

Static methods
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
2
Point Class Demo



The goal of today's project is to demonstrate
how to write a class and use it in an application.
The class we will write is a Point class that
models two-dimensional points in a Cartesian
plane of the form (x,y).
The project folder contains a GUI interface that
will allow us to declare Point objects and test
the Point class methods on those objects. We
will alternate writing Point class methods and
writing the Demo test handlers.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
3
Point Class Demo
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
4
GUI Notes



The two input textboxes are for entering Point values. The
current Point values are displayed in labels above the
textboxes. The labels' BorderStyle property is set to
FixedSingle, which gives the surrounding box. Clicking on the
Enter button is to read the input in the textbox above it, parse
the new Point, and display it in the label above the textbox
Clicking on the other buttons is to execute the corresponding
Point class method and display the results of running the
method on one or both of the displayed Point values.
The results area is a ListBox. This GUI element has an Items
property that is an ArrayList that allows elements to be added to
the end of Items and are displayed in the ListBox. Scrollbars
are automatically added when there are more items than will fit
in the box. We will be adding output strings to this ListBox.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
5
Abstract Data Types (ADTs)



A data structure is a systematic way of
organizing and accessing data.
We use an abstract model that specifies the
type of data stored and legal operations on the
data.
It is called abstract because this view is
implementation independent. We can use an
ADT just knowing what it does and not how it
does it.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
6
Abstract Data Types (ADTs)


With this abstract view concerns regarding the
data (such as validity checking) and concerns
regarding the application that uses the data
(such as the computational algorithm) can be
separated.
The design of an ADT has two parts


Declaration of the data being stored called
attributes
Method definitions of the operations that act on the
data
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
7
C# Classes


The C# class construct is used to implement
an ADT. It allows the data and the methods of
an ADT to be encapsulated in one entity called
an object.
To add a new class to a project, go to the
Project menu, choose Add Class. The Add
New Item dialog will appear. Make sure Class
is selected, type in the class name (Point.cs) at
the bottom of the dialog, and click Add.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
8
Adding a C# Class
make sure Class
is selected
type the name
of the class
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
9
Adding a C# Class

A new code file is created with an empty class
definition for Point. Note is it in the same
namespace as the GUI code.
code file entry
empty class definition
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
10
C# Classes

The modifiers public and private are used to
control the access to the items declared and
defined in a class.



Public means access is granted to all other code.
Typically is it used for the method definitions of an
class.
Private means access is restricted to the methods
of the class. Typically is it used for the attributes
being store in a class and any internal helper
methods.
This use allows for information hiding.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
11
Attributes

Class attributes are class variables declared
outside any method with the private modifier.
For our Point class, there are two attributes, the
x-coordinate and the y-coordinate of the 2D
point being modeled.
class Point
{
private double x; // x­coordinate
private double y; // y­coordinate
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
12
Attributes

Here is another way to think about Point objects
and attributes:
Point p;
Friday, March 18
x
0
y
0
CS 205 Programming for the Sciences - Lecture 26
13
Constructors




A constructor is a special method that creates an
object of the class.
A constructor's name is the same as the class name.
It does not return an object. There may be more
than one constructor as long as they have different
parameter lists. A constructor is called when the new
operator is used to create a new object.
A constructor with no parameters is called the default
constructor.
A constructor with parameters that are used to
initialize the object state is called an explicit-value
constructor.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
14
Constructors

For our Point class, we want two constructors


A default constructor that initializes both
coordinates to 0, creating the origin Point object
(0,0)
An explicit-value constructor that receives the initial
x-coordinate and y-coordinates and creates a Point
object with those coordinates.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
15
Constructors
// Default constructor: (0,0)
public Point ()
{
x = 0;
y = 0;
}
// Explicit­value constructor: // (initialX, initialY)
public Point (double initialX, double initialY)
{
x = initialX;
y = initialY;
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
16
Point Class Demo

The Demo program requires two Point
variables initialized to the default constructed
point (0,0). These variables are class variables
declared outside any methods.
class PointClassDemo
{
Point p1 = new Point();
Point p2 = new Point();
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
17
Instance Methods



Most class methods are instance methods
that are attached to an instance (i.e., a
particular object) and are allowed to access the
attributes of its object directly.
They are called using the familar dot notation:
<object var>.<method name>( ).
For our Point class, we will have instance
methods ToString( ), Magnitude( ), and
DistanceTo( ). We will look at ToString( ) first.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
18
Instance Methods

Here is another way to think about Point objects
and instance methods:
Point p;
Friday, March 18
0
y
0
)
(
g
Magnitude()
S
To
n
i
tr
x
Di
st
an
ce
To
()
CS 205 Programming for the Sciences - Lecture 26
19
ToString( ) Method


Every class has a ToString( ) instance method
that returns a string that represents the object
value. However, the default definition for this
method just returns the name of the type, so
most classes override this definition, which
requires a little extra syntax.
For the Point class, we want ToString( ) to
return a string of the form "(x,y)". This is easily
accomplished using string concatenation.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
20
ToString( ) Method
// Need override keyword, since ToString // is already defined
// No parameters, since it accesses the
// attributes directly
public override string ToString ( )
{
return "(" + x + "," + y + ")";
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
21
Testing ToString( )


We will test the ToString( ) method in the
handler for the left Enter button.
Double-click on the left Enter button to create a
button handler stub for this button, if you have
not already done so. This handler should do
the following:

Add an item to lbxResults.Items indicating the result
of the handler:
lbxResults.Items.Add ("Entered p1: " + p1.ToString());
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
22
Testing ToString( )

Build and run your program. When you click
the left Enter button, the output to the results
area should be "Entered p1: (0,0)".
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
23
Static Methods


The methods we wrote for our console
programs used the static modifier. This is
used when the method is to be called without a
class object. Since it is defined in a class, it is
called with the class name. E.g., Math.Sqrt( )
One important static method is Parse( ), which
is used when a user is expected to enter values
of the class from the keyboard. For example,
we have used double.Parse( ) and int.Parse( )
to interpret user input strings into double and int
values, respectively.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
24
Parse( ) Method


A Parse( ) method basically ignores any
punctuation in the user entered string and
converts the rest into attribute values.
For the Point class, we want to parse strings of
the form "(x,y)", where x and y are numbers.
This involves find the substrings between the
punctuation and convert them into the
coordinate values and construct a Point object
with them.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
25
Parse( ) Method

For example, for (12.5,-3.14)
find these substrings and convert to numbers for x and y

Two string methods are useful for doing this


FindIndexOf( ) receives a character to search for
and returns the index of the first occurrence of the
character if it is present, or -1 if it is not.
Substring( ) receives the starting index of a
substring and the number of characters in the
substring. It returns a (new) substring consisting of
the character at the starting index and the next
number of characters or to the end of the string,
whichever is reached first.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
26
Parse( ) Method

For now, we will assume that the user enters a
well-formed string, i.e., '(' is the first character,
')' is the last character, and there is a ',' in the
middle of the string between two substrings that
are valid numbers. Here is the basic algorithm:





Find the index of the ',' using FindIndexOf( )
Compute the start index and length of the two
substrings
Use Substring( ) to get the substrings
Use double.Parse( ) to convert them into numbers
Create and return a Point with these coordinates
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
27
Parse( ) Method
static Point Parse (string input)
{
int commaIndex = input.FindIndexOf(',');
int xStartIndex = 1;
int xLength = commaIndex – 1;
int yStartIndex = commaIndex + 1;
int yLength = input.Length – commaIndex – 2;
string xString = input.Substring(xStartIndex, xLength);
string yString = input.Substring(yStartIndex, yLength);
double newX = double.Parse(xString);
double newY = double.Parse(yString);
return new Point(newX, newY);
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
28
Testing Parse( )


To test the Parse( ) methods, we will write
handlers for the Enter buttons.
Double-click on the left Enter button to go to the
button handler this button. This handler does
the following:




Use Point.Parse( ) to parse txtPoint1.Text and
assign the result to variable p1
Set the Text property of lblPoint1 to p1.ToString( )
Clear txtPoint1.Text
Add an item to lbxResults.Items indicating the result
of the handler (this is already completed)
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
29
Testing Parse( )
private void btnEnterP1_Click(object sender,
EventArgs e)
{
p1 = Point.Parse(txtPoint1.Text);
lblPoint1.Text = p1.ToString();
txtPoint1.Text = "";
lbxResults.Items.Add
("Entered p1: " + p1.ToString());
}
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
30
Testing Parse( )


Build and run your program. You should be
able to input a Point in "(x,y)" form in the left
textbox, click on the left Enter button, and see
the label above the textbox change to the input
and the textbox become empty, along with a
message in the results area.
Repeat these steps for right Enter button
handler. This handler is exactly the same,
except that is uses p2, txtPoint2, and lblPoint2.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
31
Magnitude( ) Method

The magnitude of a Point (x,y) is its distance
from the origin (0,0) computed using the
formula:
distance=  x  y
2


2
The Point class instance method Magnitude( )
returns the magnitude its Point object.
Write the method definition for Magnitude in the
file Point.cs.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
32
Testing Magnitude( )


Double-click on the Magnitude button to get a
stub for its handler.
Write code to compute the magnitude of Points
p1 and p2, and display these results in the
result area ListBox.
Friday, March 18
CS 205 Programming for the Sciences - Lecture 26
33
Download