Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Creating and Using Classes, Methods, and Constructors in Object-Oriented Programming, Study notes of Computer Science

How to create your own classes in programming, which can store variables (data members) and functions (methods). The benefits of using methods include avoiding repeat code, promoting software reuse, and promoting good design practices. A template for defining methods and discusses access control using public and private modifiers. It also covers class constructors and using methods as accessors and mutators.

Typology: Study notes

2009/2010

Uploaded on 03/28/2010

koofers-user-7lp
koofers-user-7lp 🇺🇸

10 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Classes, Methods, Constructors
Writing Classes
We’ve been using predefined classes and objects – how do we make our own? A class is defined using
the following template. Essentially we can store two types of data in a class, variables (data members or
fields), and functions (methods). A simple format for defining a class is given below; we will add some
enhancements to it shortly.
class className {
// Define data members; i.e. variables associated with this class
public/private type varname1;
public/private type varname2;
public/private type varnameN;
// Define methods; i.e. functions associated with this class
public/private return_type methodName1(parameter_list);
public/private return_type methodName2(parameter_list);
public/private return_type methodNameN(parameter_list);
}
To add a class in Visual Studio, select “P)roject” and “Add Class” from the menu:
Each class is stored in its own file, visible in the Solution Explorer.
The term “data member” refers to a variable defined in the class.
Methods are functions defined in the class. A method is just a collection of code. The main method and
button click events are all examples of methods. The parameter list is used to pass data to the method.
Since a method is a function, we have to declare what type of value the function will return (e.g., int,
float, long, etc.) If we don’t want the method to return any value, we have a special type called void.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Creating and Using Classes, Methods, and Constructors in Object-Oriented Programming and more Study notes Computer Science in PDF only on Docsity!

Classes, Methods, Constructors

Writing Classes

We’ve been using predefined classes and objects – how do we make our own? A class is defined using

the following template. Essentially we can store two types of data in a class, variables (data members or

fields ), and functions ( methods ). A simple format for defining a class is given below; we will add some

enhancements to it shortly.

class className {

// Define data members; i.e. variables associated with this class

public/private type varname1;

public/private type varname2;

public/private type varnameN;

// Define methods; i.e. functions associated with this class

public/private return_type methodName1(parameter_list);

public/private return_type methodName2(parameter_list);

public/private return_type methodNameN(parameter_list);

To add a class in Visual Studio, select “P)roject” and “Add Class” from the menu:

Each class is stored in its own file, visible in the Solution Explorer.

The term “data member” refers to a variable defined in the class.

Methods are functions defined in the class. A method is just a collection of code. The main method and

button click events are all examples of methods. The parameter list is used to pass data to the method.

Since a method is a function, we have to declare what type of value the function will return (e.g., int,

float, long, etc.) If we don’t want the method to return any value, we have a special type called void.

Class Methods or Functions

So far, we have been working with relatively small programs using only a main function or several button

click events. For larger programs the technique of dividing a program up into manageable pieces is

typically done by constructing a number of smaller methods and then piecing them together as

modules. This type of modularization has a number of benefits:

 Avoids repeat code (reuse a method many times in one program)

 Promotes software reuse (reuse a method in another program)

 Promotes good design practices (Specify function interfaces)

 Promotes debugging (can test an individual method to make sure it works properly)

Let’s examine how to write programs using methods.

Before starting

We’ve already been using quite a few methods in our programs. Calls like WriteLine(), Show(), and

rnd.Next() are all methods that have been written by someone else that we’re using. Note how the

innards of these functions are all hidden from you – as long as you know the interface, or the

input/output behavior, you are able to use these methods in your own programs. This type of data-

hiding is one of the goals of methods and classes, so that higher-level code doesn’t need to know the

details of particular tasks.

Before starting and jumping into writing programs using methods, it is a good idea to look at the

problem you are trying to address and see how it might logically be broken up. If you jump straight

into coding you might not be defining methods that make sense and will have to throw away what you

did and start over.

Defining a Method

To define a method use the following template:

modifier return_type methodName(type1 varName1, type2 varName2, … )

Instructions

return (return_value);

Modifier is either public or private to indicate if this method is available from outside the class.

Return_type is a data type returned by the method. For example, int, float, long, another Class, or void

if we have no data to return. If we are returning a value, we must specify what value the method

MessageBox.Show(calculateDensity("Alaska", 627000, 591000)); MessageBox.Show(calculateDensity("Hawaii", 1212000, 6471)); }

In this example the method takes three parameters, a state name, population, and area. The order of

the parameters determines which value is sent in as what variable and the data types must match!

It would probably make more sense for calculateDensity to return a double that contains the formatted

density, but this does illustrate that a return value can differ from the input parameter values.

Here is another example that returns no value and takes no values as input:

private void showHelpMessage() { MessageBox.Show("If this was a real program, a " + "help message would be displayed."); } private void button1_Click(object sender, EventArgs e) { showHelpMessage(); }

Exercise: Write the method to simulate rolling two six sided dice and returning its sum:

public partial class Form1 : Form { Random rnd = new Random(); ... private void button1_Click(object sender, EventArgs e) { int diceroll; diceroll = RollDice(); Console.WriteLine(diceroll); } }

Example : In the game of Craps, a "Pass Line" bet proceeds as follows. Using two six-sided dice, the first

roll of the dice in a craps round is called the "Come Out Roll." Pass Line bets immediately win when the

shooter's come out roll is 7 or 11, and lose when the come out roll is 2 (snake eyes), 3 (cross eyes), or 12

(box cars). If 4, 5, 6, 8, 9, or 10 is rolled on the come out roll, that number becomes "the point." The

shooter now keeps rolling the dice until he rolls the point or 7 to end the round. If the shooter rolls the

point first, the pass line bet wins. If, however, the shooter rolls a 7 first (i.e. "sevens out"), a pass line bet

loses.

Write a program that plays the game of Craps using the rules stated above so that it simulates a game

without human input. Use methods for rolling the dice and rolling for the point. Count the win % for

100,000 games.

Example: Modify the Monty Hall solution to use a method(s) to determine which door to reveal instead

of duplicating almost the same code across three button click events.

Class Variables – Data Members

We already know what variables are. Variables defined inside a class are called member variables ,

because they are members of a class. They are also referred to as fields.

Member variables are accessible from code defined inside the class. If defined using public then

member variables are also accessible from code defined outside the class. If defined using private then

these variables are only accessible from code defined inside the class.

Let’s look at a simple class that contains only data members and no methods.

class Money { public int dollars; public int cents; }

Now consider another class (say a Form with a button click event) that creates objects of type Money:

private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); Money m2 = new Money(); m1.dollars = 3; m1.cents = 40; m2.dollars = 10; m2.cents = 50; Console.WriteLine(m1.dollars + " " + m1.cents); Console.WriteLine(m2.dollars + " " + m2.cents); }

The output of this program is:

When the program reaches the print statement, we have created two separate instances of the Money

object, each with different values stored in their member variables:

private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); m1.dollars = 3; // Legal, dollars is public m1.cents = 40; // ILLEGAL, cents is private }

This program will generate a compiler error since we are trying to access a private variable from outside

the class. It is considered good programming style to always use public or private to indicate the access

control of all class variables.

We can also apply the public and private modifiers to methods as well as variables, as we will see next.

Note that these modifiers only apply to variables defined in the class, not to variables defined inside a

method (e.g., we won’t use private/public on variables defined inside a button click event).

Class Constructors

Because we use classes to encapsulate data types, it is essential that class objects be initialized properly.

When we defined the Money class, we were relying upon the user to set the value for dollars and cents

outside the class. What if the client forgets to initialize the values? This can be such a serious problem

that Java provides a mechanism to guarantee that all class instances are properly initialized, called the

class constructor.

A class constructor is a method with the same name as the class and no return type. We can even make

multiple constructors with multiple parameters, to differentiate different ways a class may be initialized.

Below are two constructors for the Money class along with a method to get the currency value as a

string:

class Money { private int dollars = 0; private int cents = 0; // This constructor invoked if we create // the object with no parameters public Money() { dollars = 1; cents = 0; } // This constructor invoked if we create the object with // a dollar and cent value public Money(int inDollars, int inCents) { dollars = inDollars; cents = inCents; }

// Method to return the value as a string // It would be better to add "override" but // we will discuss that later public string toString() { return("$" + Convert.ToString(m_dollars)

  • "." + Convert.ToString(m_cents)); } }

Here is some test code:

private void button2_Click(object sender, EventArgs e) { Money m1 = new Money(); Money m2 = new Money(5, 50); Console.WriteLine(m1.ToString()); Console.WriteLine(m2.ToString()); }

When this program runs, the output is:

$1.0  From m

$5.50  From m

When we create m1, we give no parameters in Money(). This invokes the default constructor, which is

given as:

public Money()

This code initializes dollars to 1 and cents to 0.

When we create m2, we give two parameters in Money(5,50). C# will then search for a constructor that

has two parameters that match the ones provided. The constructor that is found is then invoked:

public Money(int inDollars, int inCents)

This code then sets the member variables to the input parameters, resulting in the output previously

specified.

Methods as Accessors and Mutators

Properties are a convenient way to get the same functionality as a method to set or retrieve a class

variable. In OOP terminology, it provides for an accessor (way to retrieve a class member variable) and

mutator (way to change or set a class member variable). Let’s see a typical example of an accessor and

mutator using methods. In our Money class, let’s say that we want a way to access and change the

dollar value. Since the class member variable is private, we have to make a public method to access it:

class. If we had just let the user use normal addition, then the user would have to implement this logic

themselves elsewhere.

Shortcut: Visual Studio 2008 has a built-in tool called Refactoring. If you select a class member variable,

right-click it, choose “Refactoring” and then “Encapsulate” then it will automatically create a default

property for that variable.

Book example : Job Bob Guys, page 110