1. Trang chủ
  2. » Công Nghệ Thông Tin

Collecting Data — The Class and the Array

28 338 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Collecting data — the class and the array
Tác giả Paul Deitel, Harvey Deitel
Thể loại Book chapter
Định dạng
Số trang 28
Dung lượng 549,75 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Defining a class An example of the class Vehiclemay appear as follows: public class Vehicle { public string sModel; // name of the model public string sManufacturer; // ditto public int

Trang 1

Part IIIObject-Based Programming

Trang 2

In this part

It’s one thing to declare a variable here or there and

to add them and subtract them It’s quite anotherthing to write real programs that people can use —simple people, but people nonetheless In this part, youdiscover how to group data and how to operate on thatdata You begin to think about programs as collections of

collaborating objects and start designing your own custom

objects These skills form the basis of all programmingjobs you’ll find in the classifieds

Trang 3

Chapter 6

Collecting Data — The Class

and the Array

In This Chapter

Introducing the C# class

Storing data in an object

Assigning and using object references

Creating and building arrays of objects

You can freely declare and use all the intrinsic data types — such as int,

double, and bool— to store the information necessary to make yourprogram the best that it can be For some programs, these simple variablesare enough However, most programs need a means to bundle related data in

a neat package

Some programs need to bundle pieces of data that logically belong togetherbut aren’t of the same type For example, a college enrollment applicationhandles students, each with his or her own name, rank (grade point average),and serial number Logically, the student’s name may be a string, the gradepoint average could be a double, and the serial number a long That type ofprogram needs some way to bundle these three different types of variablesinto a single structure called Student Fortunately, C# provides a structure

known as the class for accommodating groupings of unlike-typed variables.

In other cases, programs need to collect a series of like-typed objects Take,for example, a program designed to average grades A doubledoes a goodjob of representing an individual grade However, you need some type of col-lection of doublevariables to contain all the many grades that students

collect during their careers C# provides the array for just this purpose.

Finally, a real program to process student records would need to graduategroups of students before they can set out on a life of riches and fame Thistype of program needs both the class and the array concept rolled into one:arrays of students Through the magic of C# programming, you can do this

as well

Trang 4

Showing Some Class

A class is a bundling of unlike data and functions that logically belong together

into one tidy package C# gives you the freedom to foul up your classes any

way you want, but good classes are designed to represent concepts.

Analysts say that “a class maps concepts from the problem into the gram.” For example, suppose your problem is to build a traffic simulator Thistraffic simulator is to model traffic patterns for the purpose of buildingstreets, intersections, and highways (I would really like you to build a trafficsimulator that could fix the intersection in front of my house.)

pro-Any description of a problem concerning traffic would include the term vehicle

in its solution Vehicles have a top speed that must be figured into the equation.They also have a weight, and some of them are clunkers In addition, vehicles

stop and vehicles go Thus, as a concept, vehicle is part of the problem domain.

A good C# traffic simulator program would necessarily include the class

Vehicle, which describes the relevant properties of a vehicle The C#

Vehicleclass would have properties like dTopSpeed, nWeight, and bClunker

I address the stopand goparts in Chapters 7 and 8

Because the class is so central to C# programming, the chapters in Part IV ofthis book spelunk the ins and outs of classes in much more detail This chap-ter gets you started

Defining a class

An example of the class Vehiclemay appear as follows:

public class Vehicle {

public string sModel; // name of the model public string sManufacturer; // ditto

public int nNumOfDoors; // the number of doors on the vehicle public int nNumOfWheels; // you get the idea

The class name is followed by a pair of open and closed braces Within the

braces, you have zero or more members The members of a class are variables

that make up the parts of the class In this example, class Vehiclestarts with

Trang 5

the member string sModel, which contains the name of the model of thevehicle Were this a car, the model name could be Trouper II Hmm, have youever seen or heard of a Trouper I? The second member of this example

Vehicleclass is the string sManufacturer The final two properties arethe number of doors and the number of wheels on the vehicle

As with any variable, make the names of the members as descriptive as ble Although I’ve added comments to the data members, that really isn’t necessary The name of each variable says it all

possi-The publicmodifier in front of the class name makes the class universallyaccessible throughout the program Similarly, the publicmodifier in front ofthe member names makes them accessible to everything else in the program

Other modifiers are possible Chapter 11 covers the topic of accessibility inmore detail

The class definition should describe the properties of the object that aresalient to the problem at hand That’s a little hard to do right now becauseyou don’t know what the problem is, but you can see where I’m headed here

What’s the object?

Defining a Vehicledesign is not the same thing as building a car Someonehas to cut some sheet metal and turn some bolts before anyone can drive anactual vehicle A class object is declared in a similar but not identical fashion

to an intrinsic object

The term object is used universally to mean a “thing.” Okay, that isn’t too

helpful An intvariable is an intobject A vehicle is a Vehicleobject Youare a reader object I am an author Okay, forget that last one

The following code segment creates a car of class Vehicle:

Vehicle myCar;

myCar = new Vehicle();

The first line declares a variable myCarof type Vehicle, just like you candeclare a nSomethingOrOtherof class int (Yes, a class is a type, and all C#

objects are defined as classes.) The new Vehicle()command creates a cific object of type Vehicleand stores the location into the variable myCar.The newhas nothing to do with the age of myCar My car could qualify for anantique license plate if it weren’t so ugly The newoperator creates a newblock of memory in which your program can store the properties of myCar

spe-In C# terms, you say that myCaris an object of class Vehicle You also saythat myCaris an instance of Vehicle In this context, instance means “an example of” or “one of.” You can also use the word instance as a verb, as in

instantiating a Vehicle That’s what new does.

Trang 6

Compare the declaration of myCarwith that of an intvariable called num:

int num;

num = 1;

The first line declares the variable num, and the second line assigns analready-created constant of type intinto the location of the variable num.The intrinsic numand the object myCarare stored differently in memory.The constant 1does not occupy memory because both the CPU and the C#compiler already know what a 1is Your CPU doesn’t have the concept of a

Vehicle The new Vehicleexpression allocates the memory necessary todescribe a vehicle to the CPU, to C#, to the world, and yes, to the universe!

Accessing the members of an object

Each object of class Vehiclehas its own set of members The followingexpression stores the number 1 into the nNumberOfDoorsmember of theobject referenced by myCar:

myCar.nNumberOfDoors = 1;

Every C# operation must be evaluated by type as well as by value The object

myCaris an object of type Vehicle The variable Vehicle.nNumberOfDoors

is of type int(look again at the definition of the Vehicleclass) The stant 5 is also of type int, so the type of the variable on the right side of theassignment operator matches the type of the variable on the left

con-Similarly, the following code stores a reference to the strings describing themodel and manufacturer name of myCar:

myCar.sManufacturer = “BMW”; // don’t get your hopes up myCar.sModel = “Isetta”; // the Urkle-mobile

(The Isetta was a small car built during the 1950s with a single door thatopened the entire front of the car.)

An example object-based program

The simple VehicleDataOnlyprogram does the following:

 Defines the class Vehicle

 Creates an object myCar

 Assigns properties to myCar

 Retrieves those values out of the object for display

Trang 7

The code for the VehicleDataOnlyprogram is as follows:

// VehicleDataOnly - create a Vehicle object, populate its // members from the keyboard and then write it // back out

using System;

namespace VehicleDataOnly {

public class Vehicle {

public string sModel; // name of the model public string sManufacturer; // ditto

public int nNumOfDoors; // the number of doors on the vehicle public int nNumOfWheels; // you get the idea

} public class Program {

// This is where the program starts static void Main(string[] args) {

// prompt user to enter her name Console.WriteLine(“Enter the properties of your vehicle”);

// create an instance of Vehicle Vehicle myCar = new Vehicle();

// populate a data member via a temporary variable Console.Write(“Model name = “);

// wait for user to acknowledge the results Console.WriteLine(“Press Enter to terminate ”);

Console.Read();

} } }

The program listing begins with a definition of the Vehicleclass

Trang 8

The definition of a class can appear either before or after class Program— itdoesn’t matter However, you should adopt a style and stick with it BonusChapter 2 on the CD shows the more conventional technique of creating aseparate csfile to contain each class, but just put the extra class in your

Program.csfile for now

The program creates an object myCarof class Vehicleand then populateseach of the fields by reading the appropriate data from the keyboard Theinput data isn’t checked for legality The program then spits out the informa-tion just entered in a slightly different format

The output from executing this program appears as follows:

Enter the properties of your vehicle Model name = Metropolitan

Manufacturer name = Nash Number of doors = 2 Number of wheels = 4 Your vehicle is a Nash Metropolitan with 2 doors, riding on 4 wheels Press Enter to terminate

The calls to Read()as opposed to ReadLine()leave the cursor right afterthe output string This makes the user’s input appear on the same line as theprompt In addition, adding the newline character ‘\n’generates a blank linewithout the need to execute WriteLine()

Discriminating between objects

Detroit car manufacturers can track each car that they make without gettingthe cars confused Similarly, a program can create numerous objects of thesame class, as follows:

Vehicle car1 = new Vehicle();

Creating an object car2and assigning it the manufacturer name Hudson has

no effect on the car1Studebaker

In part, the ability to discriminate between objects is the real power of theclass construct The object associated with the Hudson Hornet can be cre-ated, manipulated, and dispensed with as a single entity, separate from otherobjects, including the Avanti (These are both classic automobiles, especiallythe latter.)

Trang 9

Can you give me references?

The dot operator and the assignment operator are the only two operatorsdefined on reference types, as follows:

// create a null reference Vehicle yourCar;

// assign the reference a value yourCar = new Vehicle();

// use dot to access a member yourCar.sManufacturer = “Rambler”;

// create a new reference and point it to the same object Vehicle yourSpousalCar = yourCar;

The first line creates an object yourCarwithout assigning it a value A

refer-ence that has not been initialized is said to point to the null object Any

attempt to use an uninitialized reference generates an immediate error thatterminates the program

The C# compiler can catch most attempts to use an uninitialized reference andgenerate a warning at build time If you somehow slip one past the compiler,accessing an uninitialized reference terminates the program immediately

The second statement creates a new Vehicleobject and assigns it to yourCar.The last statement in this code snippet assigns the reference yourSpousalCar

to the reference yourCar As shown in Figure 6-1, this has the effect of causing

yourSpousalCarto refer to the same object as yourCar

The following two calls have the same effect:

// build your car Vehicle yourCar = new Vehicle();

yourSpousalCar "Rambler"

Figure 6-1:

Therelationshipbetweentworeferences

to the sameobject

Trang 10

Executing this program would output Henry Jand not Kaiser Notice that

yourSpousalCardoes not point to yourCar; rather, both yourCarand

yourSpousalCarrefer to the same vehicle

In addition, the reference yourSpousalCarwould still be valid, even if thevariable yourCarwere somehow “lost” (went out of scope, for example), asshown in the following code:

// build your car Vehicle yourCar = new Vehicle();

are “lost” or nulled out

At that point — well, at some unpredictable later point, anyway — C#’s

garbage collector steps in and returns the space formerly used by that

partic-ular Vehicleobject to the pool of space available for allocating more

Vehicles(or Students, for that matter) I say a little more about garbagecollection at the end of Chapter 12

Classes that contain classes are the happiest classes in the world

The members of a class can themselves be references to other classes Forexample, vehicles have motors, which have power and efficiency factors,including displacement (I suppose a bicycle doesn’t have a displacement.)You could throw these factors directly into the class as follows:

public class Vehicle {

public string sModel; // name of the model public string sManufacturer; // ditto

public int nNumOfDoors; // the number of doors on the vehicle public int nNumOfWheels; // you get the idea

public int nPower; // power of the motor [horsepower]

public double displacement; // engine displacement [liter]

Trang 11

However, power and engine displacement are not properties of the car Forexample, my son’s Jeep comes with two different motor options with drasti-cally different horsepower The 2.4-liter Jeep is a snail while the same car out-fitted with the 4.0-liter engine is quite peppy.

The motor is a concept of its own and deserves its own class, as follows:

public class Motor {

public int nPower; // power [horsepower]

public double displacement; // engine displacement [liter]

}

You can combine this class into the Vehicleas follows:

public class Vehicle {

public string sModel; // name of the model public string sManufacturer; // ditto

public int nNumOfDoors; // the number of doors on the vehicle public int nNumOfWheels; // you get the idea

public Motor motor;

}

Creating myCarnow appears as follows:

// first create a Motor Motor largerMotor = new Motor();

Console.WriteLine(“The motor displacement is “ + m.displacement);

Or, you can access it directly, as shown here:

Console.Writeline(“The motor displacement is “ + sonsCar.motor.displacement);

Either way, you can only access the displacementthrough the Motor

Trang 12

This example is bundled in the simple program VehicleAndMotoron theenclosed CD, not shown in full here.

Generating static in class members

Most data members of a class describe each object Consider the Carclass,

The license plate ID is an object property, meaning that it describes each

object of class Caruniquely For example, thank goodness that my car has adifferent license plate from yours; otherwise, you may not make it out of yourdriveway, as shown in the following code:

Car cousinsCar = new Car();

cousinsCar.sLicensePlate = “XYZ123”;

Car yourCar = new Car();

yourCar.sLicensePlate = “ABC789”;

However, some properties exist that all cars share For example, the number

of cars built is a property of the class Carbut not of any one object These

are called class properties and are flagged in C# with the keyword static, asfollows:

public class Car {

public static int nNumberOfCars; // the number of cars built public string sLicensePlate; // the license plate ID }

Static members are not accessed through the object Instead, you accessthem via the class itself, as the following code snippet demonstrates:

// create a new object of class Car Car newCar = new Car();

newCar.sLicensePlate = “ABC123”;

// now increment the count of cars to reflect the new one Car.nNumberOfCars++;

The object member newCar.sLicensePlateis accessed through the object

newCar, while the class (static) member Car.nNumberOfCarsis accessedthrough the class Car All Cars share the same nNumberOfCarsmember

Trang 13

Defining const data members

One special type of static is the constdata member, which represents a stant You must establish the value of a constvariable in the declaration, andyou may not change it anywhere within the program, as shown in the follow-ing code:

con-class Program {

// number of days in the year (including leap day) public const int nDaysInYear = 366;

public static void Main(string[] args) {

// this is an array, covered later in this chapter int[] nMaxTemperatures = new int[nDaysInYear];

for(int index = 0; index < nDaysInYear; index++) {

// accumulate the maximum temperature for each // day of the year

} } }

You can use the constant nDaysInYearin place of the value 366 anywherewithin your program The constvariable is useful because it can replace amysterious constant such as 366 with the descriptive name nDaysInYeartoenhance the readability of your program

Actually, C# provides a second way to declare constants You can preface avariable declaration with the readonlymodifier, like so:

public readonly int nDaysInYear = 366; // this could also be static

As with const, after you assign the initial value, it can’t be changed Althoughthe reasons are too technical for this book, the readonlyapproach to declar-ing constants is preferable to const

An alternative convention also exists for naming constants Instead of namingthem like variables (as in nDaysInYear), many programmers prefer to useuppercase letters separated by underscores, as in DAYS_IN_YEAR This con-vention separates constants clearly from ordinary read-write variables

The C# Array

Variables that contain single values are all well and good Even class structuresthat can describe compound objects like a vehicle are critical But you alsoneed a construct for holding a set of objects, such as Bill Gates’s extensive

Trang 14

collection of vintage cars The built-in class Arrayis a structure that can tain a series of elements of the same type (all int values, all doublevalues,and so on, or all Vehicleobjects, Motorobjects, and so on).

con-The argument for the array

Consider the problem of averaging a set of 10 floating point numbers Each ofthe 10 numbers requires its own doublestorage (averaging intvariablescould result in rounding errors, as described in Chapter 3), as follows:

double dAverage = dSum / 10;

Listing each element by name is tedious Okay, maybe it’s not so tediouswhen you have only 10 numbers to average, but imagine averaging 100 oreven 1,000 floating point values

The fixed-value array

Fortunately, you don’t need to name each element separately C# providesthe array structure that can store a sequence of values Using an array, youcan rewrite the preceding code segment as follows:

Ngày đăng: 04/10/2013, 21:20

TỪ KHÓA LIÊN QUAN