• Tidak ada hasil yang ditemukan

First Example: Defining and Using a Class

Bad Ver sion

Step 4 Development: Finishing Up

4.1 First Example: Defining and Using a Class

The most economical and effective means of on-campus transportation is without doubt a bicycle. Suppose we want to develop a program that tracks the bicycles by assigning to them some form of identification number along with the relevant information, such as the owner’s name and phone number. To develop such a Java program, we need to design many different types of objects. For example, we need objects to handle input, output, data storage, and other computational tasks. Among the many types of objects necessary for this program, we will design one class here that models a bicycle. There’s no such Bicycleclass among the standard classes, of course, so we need to define one ourselves. We will learn how to define the Bicycle class in this section. We will start with a very simplistic Bicycleclass. Using this class, we can only assign and retrieve the owner’s name. Before we look inside the Bicycleclass and explain how the class is defined, let’s first look at how we might use it in our program. The following sample program creates two Bicycleobjects, assigns the owners’ names to them, and displays the information:

S

class BicycleRegistration {

public static void main(String[] args) { Bicycle bike1, bike2;

String owner1, owner2;

bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setOwnerName("Ben Jones");

//Output the information

owner1 = bike1.getOwnerName( );

owner2 = bike2.getOwnerName( );

System.out.println(owner1 + " owns a bicycle.");

System.out.println(owner2 + " also owns a bicycle.");

} }

Here’s the definition of the Bicycleclass. To distinguish it from the standard classes, we call the Bicycleand other classes we define programmer-defined classes.

programmer- defined classes

class Bicycle { // Data Member

private String ownerName;

//Constructor: Initialzes the data member public Bicycle( ) {

ownerName = "Unknown";

}

//Returns the name of this bicycle's owner public String getOwnerName( ) {

return ownerName;

}

//Assigns the name of this bicycle's owner public void setOwnerName(String name) {

ownerName = name:

} }

The dependency diagram between the two classes is as follows:

When this program is executed, we get the following output on the standard output window:

Adam Smith owns a bicycle.

Ben Jones also owns a bicycle.

This main class should look very familiar to all of us. The key difference lies in the use of theBicycleclass instead of the standard classes we have been using so far.

The way we use theBicycleclass is the same. For example, we create aBicycleobject bike2by calling thenewoperator, and we assign the name of its owner by executing

bike2 = new Bicycle( );

bike2.setOwnerName("Ben Jones");

BicycleRegistration Bicycle

To get the name of the owner of bike2, we write bike2.getOwnerName()

And we can assign the returned value to a variable if we write String owner2;

...

owner2 = bike2.getOwnerName();

Although it is not a requirement, we will save one class definition per file to keep things simple. For the file name, we will use the name of the class followed by the javasuffix. So, we save the Bicycleclass in a file named Bicycle.java.

Save one class definition per file. Use the name of the class followed by the suffix java as the file name. Follow this rule to avoid any unnecessary complications.

For this sample program, we have created two classes—BicycleRegistration (the main class) and Bicycle. So there are two source files for this program.

TheBicycleClass

Now let’s study the Bicycle class. Table 4.1 lists the three methods of the Bicycle class and their description.

Here’s a template for the Bicycleclass declaration:

class Bicycle { //data members //methods }

BicycleRegistration.java Bicycle.java

T able

Table 4.1

The three methods of the Bicycleclass. The first method is called a constructor

Method Parameter Description

Bicycle None Initializes the owner’s name toUnassigned.

getOwnerName None Returns the owner’s name.

setOwnerName Name of the Assigns the bicycle owner’s name to the passed owner (string) value.

The class declaration begins with the reserved word classfollowed by the name.

Any valid identifier that is not a reserved word can be used as the class name.

We define the three methods inside the class declaration. But before we can provide the method definitions, we need to consider the data members of the Bicycle class. Remember, in Section 1.3, we stated that data members of a class are the data values associated with the class or instances of the class, such as the current balance of an Accountobject. What would be the data members of Bicycleobjects? We need to know the owner’s name of every Bicycleobject, so we’ll define one data member to store the owner’s name. The data members of a class are declared within the class declaration. Here’s how we define the data member ownerNameof the Bicycleclass:

class Bicycle {

private String ownerName;

//definitions for the constructor,

//getOwnerName, and setOwnerName methods come here }

TheownerNamedata member is an instance variable (we will learn how to de- clare class constants later in this chapter and class variables in Chap. 7). Remember that, in Section 1.3, we defined an instance variable as the data member we associate to an individual instance and whose value can change over time. In other words, each instance of the class will have its own copy. After the twoBicycleobjects are created and assigned their respective names by program, we have the following memory state:

The syntax for the data member declaration is

<modifier-list> <data type> <name> ;

where <modifier-list>designates different characteristics of the data member, <data type>the class name or primitive data type, and <name>the name of the data mem- ber. Here’s how the general syntax corresponds to the actual declaration:

Modifier

private ownerName ;

Data Type

String

Name bike1

“Adam Smith”

:Bicycle ownerName

bike2

“Ben Jones”

:Bicycle ownerName

In this example, the data member has one modifier named private. This modifier is called an accessibility modifier, or a visibility modifier, and it restricts who can have a direct access to the data member. If the modifier is private, then only the methods defined in the class can access it directly. We will provide a more detailed discus- sion of the accessibility modifiers in Section 4.6. For now, it suffices to remember that data members are declared privatefor the most part.

Now that the necessary data member is taken care of, we are ready to define the three methods. We start with the setOwnerNamemethod, which is declared as

public void setOwnerName(String name) { ownerName = name;

}

The syntax for defining a method, as given in Chapter 2, is

<modifiers> <return type> <method name> ( <parameters> ) {

<statements>

}

The following diagram shows how the components in the general syntax cor- respond to the actual elements in the setOwnerNamemethod:

We explained in Chapter 1 that methods may or may not return a value. A method that does not return a value, such as this setOwnerNamemethod, is declared as void. It is called a void method. The accessibility modifier for the setOwnerName method is declared as public. This means the program that uses the Bicycleclass can access, or call, this method. It is possible (and could be useful) to declare a method as private. If a method is declared as private, then it cannot be called from the pro- gram that uses the class. It can only be called from the other methods of the same class. For now we will limit our discussion to publicmethods. Here we declare all methods as publicbecause we want the programs that use the Bicycleclass to be able to call them. We will go over the use of privatemethods later in the chapter.

Modifier

public

}

setOwnerName ( String name ) { Statements Return Type

void

Method Name

Parameter

ownerName = name;

This refers to instance variable ownerName.

This refers to parameter name.

accessibility modifier

void method

The getOwnerNamemethod is defined as follows:

public String getOwnerName( ) { return ownerName;

}

The following diagram shows how the components in the general syntax corre- spond to the actual elements in the getOwnerNamemethod:

This is a value-returning method. When this method is called, it returns a value to the caller. The getOwnerNamemethod returns a string value—the value of instance variable ownerName—so its return type is declared as String. A value- returning method must include a returnstatement of the format

return <expression> ;

The data type of <expression> must be compatible with the declared return type of the method. For example, if the return type is int, then the data type of the returned value must be compatible with int(data types int, short, and byte are all compatible with int). Data type compatibilites are explained in Section 3.2.

If a method returns a value, then we can include a call to the method in an ex- pression itself. For example, instead of writing

Bicycle bike;

...

String owner = bike.getOwnerName( );

System.out.println(owner + "owns a bike.");

we can write

Bicycle bike;

...

System.out.println(bike.getOwnerName( ) + "owns a bike.");

Modifier

public

}

getOwnerName ( ) { Statements Return Type

String

Method Name

Parameter

return ownerName;

This refers to instance variable ownerName.

value-returning method

returnstate- ment syntax

A method that returns information about an object (such as who is the owner of a bicycle) is called an accessor. The getOwnerNamemethod is an accessor. An inverse of an accessor that sets a property of an object is called a mutator. The setOwnerNamemethod is a mutator. Accessors and mutators are commonly called get and set methods, respectively.

A value-returning method can include more than one returnstatement. The use of multiple returnstatements make sense only in the context of the control statements, which we will discuss in Chapters 5 and 6. We will be seeing examples of multiple returnstatements in these chapters.

The first method defined in the Bicycleclass is a special method called a con- structor. Aconstructoris a special method that is executed when a new instance of the class is created, that is, when the newoperator is called. Here’s the constructor for the Bicycleclass:

public Bicycle( ) {

ownerName = "Unassigned";

}

It follows the general syntax

public <class name> ( <parameters> ) {

<statements>

}

where <class name>is the name of the class to which this constructor belongs. The following diagram shows how the components in the general syntax correspond to the actual elements in the constructor of the Bicycleclass:

Notice that a constructor does not have a return type and, consequently, will never include a returnstatement. The modifier of a constructor does not have to be public, but non-publicconstructors are rarely used. This example shows no parame- ters, but it is very common to define a constructor with two or three parameters. We will see an example of a constructor that accepts two parameters in Section 4.5.

Until then, we will define only a zero-parameter constructor.

The purpose of the Bicycleconstructor is to initialize the data member to a value that reflects the state to which the real name is not yet assigned. Since a constructor is executed when a new instance is created, it is the most logical place

Modifier

public

}

( ) {

Statements Class Name

Bicycle

Parameters

ownerName = "Unassigned";

accessor mutator

constructor

to initialize the data members and perform any other initialization tasks. Figure 4.1 shows a sequence of state-of-memory diagrams illustrating the effects of executing the constructor and the setOwnerNamemethod of the Bicycleclass.

We stated earlier that the Bicycleclass has three methods, of which one is a constructor. However, a constructor is distinct from other “regular” methods, so it is more common to state that the Bicycleclass has one constructor and two methods.

Figure 4.1 A sequence of state-of-memory diagrams that illustrate the effects of executing the constructor and the setOwnerNamemethod of the Bicycleclass.

bike bike

“Unassigned”

:Bicycle ownerName Bicycle bike;

bike = new Bicycle( );

Bicycle bike;

bike

“Jon Java”

:Bicycle ownerName Bicycle bike;

bike = new Bicycle( );

bike.setOwnerName("Jon Java");

Instead of saying “a class has three methods including one constructor,” it is more common to say “a class has one constructor and two methods.” We will use the later expression in this book.

We will provide a more detailed discussion on constructors in Section 4.5.

The class diagram that lists the data member, the constructor, and two meth- ods of the Bicycleclass is shown in Figure 4.2.

In listing the data members and methods of a class, we will use the following convention:

We list the data members first, then the constructor, and finally the methods.

Within each group, we list elements in alphabetical order. Keep in mind that this convention for grouping elements and ordering them within a group is for our convenience. The Java compiler does not care how we list the data members and methods.

class <class name> {

// data members // constructor // methods }

Data Member Listing

Method Listing

We include the data type of an argument passed to the method.

Bicycle ownerName Bicycle( ) getOwnerName( ) setOwnerName( String )

Figure 4.2 A class diagram of the Bicycleclass with two methods and one data member.

The Java compiler does not care how we order the methods and data members in the class declaration. We adopt the listing convention to make the class declaration easier for us to follow.

Compiling and RunningBicycleRegistration

Up until now, when we ran the sample programs, we simply compiled and executed the main class. That’s all we need to do because the main class is the only class we

class listing convention

created for the sample programs. But for this sample program, we have created two classes—BicycleRegistration (the main class) and Bicycle. So there are two source files for this program.

From now on, we will use the name of the main class to refer the whole pro- gram. To run the BicycleRegistrationprogram, we must first compile the two source files and then run the main class. Here are the steps we follow to run this sample program (we will illustrate the steps using the minimalist approach, see App. A):

1. Compile the Bicycleclass.

javac Bicycle.java

2. Compile the BicycleRegistrationclass.

javac BicycleRegistration.java 3. Run the BicycleRegistrationclass.

java BicycleRegistration

There is one last thing to remember. The way the classes are written now, the easiest way to manage a program that includes multiple programmer-defined classes is to save the source files in the same folder (directory). We will learn how to organize classes into a package in Chapter 7 so we can manage the organization of classes in a more effective manner. Until then, just remember to place all sources files for a program in the same folder. If you don’t do this, the Java compiler and interpreter may not be able to compile and run the program.

BicycleRegistration.java

Source files for the BicycleRegistration program Bicycle.java These files must

be stored in the same folder.

Place all source files for a program in the same folder (directory).

It is not necessary to create a separate folder for each program, though. In other words, one folder can contain source files for multiple programs. For example,

we could create one folder to place all source files for this chapter’s sample code.

However, we recommend that students create a separate folder for each program- ming assignment or lab project for easy management.

The class declaration can be preceded with the accessibility modifier publicor private. For now, we do not use any accessibility modifier for the class dec- laration. We will discuss the issue when we discuss a package organization in Chapter 7.

1. Extend the Bicycleclass by adding the second data member tagNoof type String. Declare this data member as private.

2. Add a new method to the Bicycleclass that assigns a tag number. This method will be called as follows:

Bicycle bike;

bike = new Bicycle( );

...

bike.setTagNo("2004–134R");

3. Add a another method to the Bicycleclass that returns the bicycle’s tag number.

This method will be called as follows:

Bicycle bike;

bike = new Bicycle( );

...

String tag = bike.getTagNo( );