CLASS AND METHOD DEFINITIONS

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 299 - 329)

The greatest invention of the nineteenth century was the invention of the method of invention.

ALFRED NORTH WHITEHEAD, SCIENCE AND THE MODERN WORLD

A Java program consists of objects of various class types, interacting with one another. Before we go into the details of how you define your own classes and objects in Java, let’s review and elaborate on what we already know about classes and objects.

Objects in a program can represent either objects in the real word—

like automobiles, houses, and employee records—or abstractions like colors, shapes, and words. A class is the definition of a kind of object. It is like a plan or a blueprint for constructing specific objects. For example, Figure 5.1 describes a class called Automobile. The class is a general description of what an automobile is and what it can do.

Objects in a program can represent real- world things or abstractions

FIGURE 5.1 A Class as a Blueprint

Class description

Second Instantiation:

Object name: suesCar First Instantiation:

Object name: patsCar

Third Instantiation:

Object name: ronsCar

amount of fuel: 14 gallons speed: 0 miles per hour license plate: "SUES CAR"

amount of fuel: 10 gallons speed: 55 miles per hour license plate: "135 XJK"

amount of fuel: 2 gallons speed: 75 miles per hour license plate: "351 WLF"

Class Name: Automobile Data:

amount of fuel__________

speed __________

license plate __________

Methods (actions):

accelerate:

How: Press on gas pedal.

decelerate:

How: Press on brake pedal.

Objects that are instantiations of the class Automobile

264 CHAPTER 5 / Defining Classes and Methods

Objects of this class are particular automobiles. The figure shows three Automobile objects. Each of these objects satisfies the class definition of an Automobile object and is an instance of the Automobile class. Thus, we can create, or instantiate, several objects of the same class. The objects here are individual automobiles, while the Automobile class is a generic description of what an automobile is and does. This is, of course, a very simplified version of an automobile, but it illustrates the basic idea of what a class is. Let’s look at some details.

A class specifies the attributes, or data, that objects of the class have.

The Automobile class definition says that an Automobile object has three attributes or pieces of data: a number telling how many gallons of fuel are in the fuel tank, another number telling how fast the automobile is moving, and a string that shows what is written on the license plate. The class definition has no data—that is, no numbers and no string. The individual objects have the data, but the class specifies what kind of data they have.

The class also specifies what actions the objects can take and how they accomplish those actions. The Automobile class specifies two actions:

accelerate and decelerate. Thus, in a program that uses the class Automobile, the only actions an Automobile object can take are accelerate and decelerate. These actions are described within the class by methods.

All objects of any one class have the same methods. In particular, all objects of the class Automobile have the same methods. As you can see in our sample Automobile class, the definitions of the methods are given in the class definition and describe how objects perform the actions.

The notation in Figure 5.1 is a bit cumbersome, so programmers often use a simpler graphical notation to summarize some of the main properties of a class. This notation, illustrated in Figure 5.2, is called a UML class diagram, or simply a class diagram. UML is an abbreviation for Universal Modeling Language. The class described in Figure 5.2 is the same as the one described in Figure 5.1. Any annotations in Figure 5.2 that are new will be explained later in the chapter.

An instance of a class is an object

A class is like a blueprint for creating objects

A class specifies an object’s attributes and defines its behaviors as methods

Use a UML class diagram to help design a class

FIGURE 5.2 A Class Outline as a UML Class Diagram

Automobile Class name

Data

Methods (actions) – fuel: double

– speed: double – license: String

+ accelerate(double pedalPressure): void + decelerate(double pedalPressure): void

/PUJDFBGFXNPSFUIJOHTBCPVUBDMBTTBOEUIFPCKFDUTUIBUJOTUBOUJBUFUIF class. Each object has a name. In Figure 5.1, the names are patsCar,suesCar, andronsCar. In a Java program, these object names would be variables of type Automobile. That is, the data type of the variables is the class type Automobile.

Before we get further into the nitty-gritty of defining a simple class, let’s review some of the things we said in Chapter 1 about storing classes in files and compiling them.

Class Files and Separate Compilation

8IFUIFSZPVVTFBDMBTTUBLFOGSPNUIJTCPPLPSPOFUIBUZPVXSJUFZPVSTFMG you place each Java class definition in a file by itself. There are exceptions to this rule, but we will seldom encounter them, and we need not be concerned about them yet. The name of the file should begin with the name of the class and end in .java4PJGZPVXSJUFBEFGJOJUJPOGPSBDMBTTDBMMFEAutomobile, it should be in a file named Automobile.java.

You can compile a Java class before you have a program in which to use it.

The compiled bytecode for the class will be stored in a file of the same name, but ending in .class rather than .java4PDPNQJMJOHUIFGJMFAutomobile.java will create a file called Automobile.class. Later, you can compile a program file that uses the class Automobile, and you will not need to recompile the class definition for Automobile. This naming requirement applies to full QSPHSBNT BT XFMM BT UP DMBTTFT /PUJDF UIBU FWFSZ QSPHSBN IBWJOH Bmain method has a class name at the start of the file; this is the name you need to use for the file that holds the program. For example, the program you will see later in Listing 5.2 should be in a file named DogDemo.java. As long as all the classes you use in a program are in the same directory as the program file, you need not worry about directories. In Chapter 6, we will discuss how to use files from more than one directory.

Each class is in a separate file

PROGRAMMING EXAMPLE Implementing a DogClass To introduce the way that Java classes are defined let’s create a simple class to represent a dog. Thus, we name our class Dog in Listing 5.1. Although its simplicity makes this first example easier to explain, it violates several important design principles. As we progress through this chapter we will discuss the weaknesses of the example’s design and show how to improve it.

Each object of the Dog class stores the name, breed, and age of a dog.

Additionally, each object has two actions, defined by the methods writeOutput andgetAgeInHumanYears. The writeOutput method outputs the data stored about the dog and the getAgeInHumanYears method approximates the dog’s equivalent age as if it were a human. Both the data items and the methods are

266 CHAPTER 5 / Defining Classes and Methods

sometimes called members of the object because they belong to the object.

8FXJMMDBMMUIFEBUBJUFNTinstance variables. In the following subsections we will discuss the instance variables and then the methods.

Instance variables and methods are members of a class.

LISTING 5.1 Definition of a Dog Class public class Dog

{

public String name;

public String breed;

public int age;

public void writeOutput() {

System.out.println("Name: " + name);

System.out.println("Breed: " + breed);

System.out.println("Age in calendar years: " + age);

System.out.println("Age in human years: " + getAgeInHumanYears());

System.out.println();

}

public int getAgeInHumanYears() {

int humanAge = 0;

if (age <= 2) {

humanAge = age * 11;

} else {

humanAge = 22 + ((age-2) * 5);

}

return humanAge;

} }

Later in this chapter we will see that the modifier public for instance variables should be replaced with private.

Instance Variables

The following three lines from the start of the class definition in Listing 5.1 define three instance variables:

public String name;

public String breed;

public int age;

The word public simply means that there are no restrictions on how these instance variables are used. You will soon see that using public here is a bad idea, but let’s ignore that for now. Each of these lines declares one instance

WBSJBCMF/PUJDFUIBUFBDIJOTUBODFWBSJBCMFIBTBEBUBUZQF'PSFYBNQMFUIF instance variable name is of type String.

You can think of an object of the class as a complex item having instance variables inside of it. In this case, the instance variables are called name, breed, and age. Each object, or instance, of the class has its own copy of these three instance variables, which is why they are called instance variables.

The program in Listing 5.2 demonstrates how to use the Dog class and handle these instance variables.

LISTING 5.2 Using the Dog Class and Its Methods public class DogDemo

{

public static void main(String[] args) {

Dog balto = new Dog();

balto.name = "Balto";

balto.age = 8;

balto.breed = "Siberian Husky";

balto.writeOutput();

Dog scooby = new Dog();

scooby.name = "Scooby";

scooby.age = 42;

scooby.breed = "Great Dane";

System.out.println(scooby.name + " is a " + scooby.breed + ".");

System.out.print("He is " + scooby.age +

" years old, or ");

int humanYears = scooby.getAgeInHumanYears();

System.out.println(humanYears + " in human years.");

} }

Sample Screen Output Name: Balto

Breed: Siberian Husky Age in calendar years: 8 Age in human years: 52 Scooby is a Great Dane.

He is 42 years old, or 222 in human years.

The following line from Listing 5.2 creates an object of type Dog and attaches the name balto to the object:

Dog balto = new Dog();

268 CHAPTER 5 / Defining Classes and Methods

The variables balto and scooby reference distinct Dog objects, each with their own instance variables of name,breed, and age. You can refer to one of these instance variables by writing the object name followed by a dot and then the instance variable’s name. For example,

balto.name

4JODFname is of type String,balto.name is a variable of type String and can be used anywhere that you can use a variable of type String. For example, all of the following are valid Java statements:

balto.name = "Balto";

System.out.println("The dog's name is " + balto.name);

String niceName = balto.name;

4JODF FBDI PCKFDU PG UZQFDog has its own three instance variables, if your program also contained the statement

Dog scooby = new Dog();

Thenbalto.name and scooby.name would be two different instance variables that might have different string values. In Listing 5.2 they do have different values since balto.name is set to “Balto” and scooby.nameJTTFUUPi4DPPCZw

FAQ Why do we need new?

In Java, new is a unary operator that we use to create objects of a class.

Whennew is used in an expression such as Dog scooby = new Dog();

it creates an object of the class Dog. The new operator then returns the memory address of the object. The preceding Java statement assigns this address to the variable scooby. An object can have variables inside of it, namely, the instance variables of the object. The new operator places these instance variables inside of the object when it creates the object.

FAQ If the program in Listing 5.2 is a class, why doesn’t it have instance variables?

A program is simply a class that has a method named main. But a program can have other methods and can have instance variables, even though none of the programs we have written so far have instance variables or any methods other than main.

Methods

8IFOZPVVTFBNFUIPEZPVBSFTBJEUPJOWPLFPSDBMMJU:PVIBWFBMSFBEZ invoked methods. For example, your programs have invoked the method nextInt using objects of the class Scanner. You have also invoked the method println of the object System.out, as in the following statement:

System.out.println("Hello out there!");

Java has two kinds of methods:

t .FUIPETUIBUSFUVSOBTJOHMFJUFN

t .FUIPETUIBUQFSGPSNTPNFBDUJPOPUIFSUIBOSFUVSOJOHBOJUFN

The methodnextInt is an example of a method that returns a single value, one of type int. The method println is an example of a method that performs TPNFBDUJPOPUIFSUIBOSFUVSOJOHBTJOHMFWBMVF.FUIPETUIBUQFSGPSNTPNF action other than returning a value are called void methods.

You invoke, or call, a method

Two kinds of methods

REMEMBER Two Kinds of Methods

Java has two kinds of methods: those that return a single value or object and those that perform some action other than returning an item. These two different kinds of methods are normally used in slightly different ways.

Let’s review how you invoke a method. The method nextInt of the class ScannerJTBNFUIPEUIBUSFUVSOTBTJOHMFWBMVF4VQQPTFUIFEFDMBSBUJPO

int theNextInteger;

is in a program. The following statement invokes the method nextInt using the object keyboard, which we assume is an object of the class Scanner:

theNextInteger = keyboard.nextInt();

Let’s look at this method invocation in more detail.

A method defined in a class is usually invoked using an object of that class. You write the receiving object name—such as keyboard—followed by a dot, and then the name of the method—such as nextInt—and finally a set of parentheses that can contain arguments for the method. If the method is one that returns a single quantity, such as the method nextInt, you can use this method invocation anywhere that you can use an item of the type returned by the method. The method nextInt returns a value of type int, and so you can use the expression

keyboard.nextInt()

Calling a method that returns a value

270 CHAPTER 5 / Defining Classes and Methods

anywhere that it is valid to use a value of type int. The expression behaves as if it were replaced by the value returned. For example, since the assignment statement

int data = 6;

is valid, so is the statement

int data = keyboard.nextInt();

.FUIPETUIBUQFSGPSNTPNFBDUJPOPUIFSUIBOSFUVSOJOHBTJOHMFRVBOUJUZ are invoked in a similar way. But since they do not return a value, their invocations stand alone; they are not embedded in another Java statement.

For example, the following statement includes an invocation of the method println:

System.out.println("Hello out there!");

This method call causes the sentence Hello out there! to be displayed on the screen.

Calling the method writeOutput for the class Dog, as in Listing 5.2 has a similar effect, except that you do not have to tell writeOutput what to write by including arguments inside the parentheses. Instead, the method writeOutput gets the information it needs from its receiving object.

For example, the latter part of the program in Listing 5.2 sets the values of the instance variables of the object balto using the following three assignment statements:

balto.name = "Balto";

balto.age = 8;

balto.breed = "Siberian Husky";

The program then uses the following statement to display these values:

balto.writeOutput();

The method writeOutput gets data from the object balto to produce the output

Name: Balto

Breed: Siberian Husky Age in calendar years: 8 Age in human years: 52

At the end of Listing 5.2 we perform essentially the same task as the writeOutput method by accessing the instance variables directly from the scoobyPCKFDU8IJMFUIJTDBOCFVTFGVMUPHFOFSBUFBDVTUPNJ[FENFTTBHFJG we are happy with the writeOutput output then the last four lines of main can be simplified down to

scooby.writeOutput();

Calling a void method

REMEMBER Invoking (Calling) a Method

You invoke a method by writing the name of the receiving object followed by a dot, the name of the method, and finally a set of parentheses that can contain arguments providing information for the method.

RECAP Calling a Method That Returns a Quantity

If a method returns a single quantity, you can invoke it anywhere that you can use a value of the type returned by the method. For example, the following statement includes an invocation of the method getAgeInHumanYears, and the value returned is assigned to the int variablehumanYears:

humanYears = scooby.getAgeInHumanYears();

RECAP Calling a void Method

If a method performs some action other than returning a single quantity, you write its invocation followed by a semicolon. The resulting Java statement performs the action defined by the method. For example, the following is an invocation of the method writeOutput for the object balto:

balto.writeOutput();

This method invocation displays several lines of output on the screen.

FAQ What about main? If it is indeed a method, why don’t I invoke it?

When you run a program, the system invokes the void method named main. Of course, this is a special kind of method invocation—one that you do not write—but it is a method invocation nonetheless.

272 CHAPTER 5 / Defining Classes and Methods

Defining void Methods

Let’s look at the definition of the method writeOutput to see how method definitions are written. The definition is given in Listing 5.1 and is repeated here:

public void writeOutput() {

System.out.println("Name: " + name);

System.out.println("Breed: " + breed);

System.out.println("Age in calendar years: " + age);

System.out.println("Age in human years: " + getAgeInHumanYears());

System.out.println();

}

All method definitions appear inside the definition of the class to which they belong. If you look at Listing 5.1, you will see that this method definition is inside the definition of the class Dog. This means that the method can be used only with objects of the class Dog.

For now, our method definitions begin with the keyword public. The word public indicates that there are no special restrictions on the use of the method. Later in this chapter, you will see that the word public can sometimes be replaced by other modifiers that restrict the use of the method.

For a method like writeOutput that does not return a value, you next write the keyword void. This keyword indicates that the method does not return a value and is the reason why this kind of method is called a void method. After the keyword void, you write the name of the method and a pair of parentheses. The parentheses enclose representations of any arguments that the method will need. In our example, no extra information is needed, and so there is nothing inside the parentheses. Later in the chapter, you will see examples of the sorts of things that might appear inside these parentheses for other method definitions. This first part of the method definition is called the heading for the method. The heading is normally written on a single line, but if it is too long for one line, it can be broken into two or more lines.

After the heading comes the rest of the method definition, which is called thebody. The statements in the body of the method definition are enclosed between braces {}. Any statement or declaration that you can place in a program can appear within the body. You can use instance variables within the body. Any other variables used in a method definition must be declared XJUIJOUIBUNFUIPEEFGJOJUJPO4VDIWBSJBCMFTBSFDBMMFElocal variables.

8IFOBvoid method is invoked, it is as if the method invocation were replaced by the body of the method definition and its statements were then executed. There are some subtleties about this replacement process, but for the simple examples we will look at now, think of the body of the method definition as literally replacing the method invocation. Eventually, you’ll want to think of the method definition as defining an action to be taken, rather than as a list of statements to substitute for the method invocation, but this A definition of a

void method

A method definition has a heading and a body

Local variables are those declared within a method’s body

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 299 - 329)

Tải bản đầy đủ (PDF)

(987 trang)