CarrCh01v2

CarrCh01v2 - C H A P T E R 1 Java Classes CONTENTS Objects...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: C H A P T E R 1 Java Classes CONTENTS Objects and Classes Using the Methods in a Java Class References and Aliases Arguments and Parameters Defining a Java Class Method Definitions Passing Arguments A Definition of the Class Name Constructors The Method toString Static Fields and Methods Packages The Java Class Library PREREQUISITES Appendix A Java Essentials OBJECTIVES After studying this chapter, you should be able to G G G G G G G G G Create an object of a class Call a method given its signature Describe the effect of a given invocation of a method Write a method definition Write a class definition Describe, define, and use constructors Describe the use of the access modifiers public and private Describe the use of static methods and data fields Create and use packages 5 6 CHAPTER 1 Java Classes This chapter reviews the use and creation of Java classes, methods, and packages. Even if you are familiar with this material, you should at least skim it to learn our terminology. Objects and Classes 1.1 An object is a program construct that contains data and can perform certain actions. Like the objects in the world around us, the objects in a Java program interact with one another to accomplish a particular task. Thus, object-oriented programming, or OOP, views a program as a sort of world consisting of objects that interact with one another by means of actions. For example, in a program that simulates automobiles, each automobile is an object. The actions that an object can take are called methods. The methods that an automobile object can perform might be moving forward, moving backward, accelerating, and so on. When you ask an object to perform an action, you invoke, or call, a method. Objects of the same kind are said to have the same type and are in the same class. A class specifies the kind of data the objects of that class have. A class also specifies what actions the objects can take and how they accomplish those actions. When you define a class in Java, the class is like a plan or a blueprint for constructing specific objects. For example, Figure 1-1 describes a class called Automobile and shows three Automobile objects. The class is a general description of what an automobile is and what it can do. Objects of the class Automobile are particular automobiles. Each is an instance of the class and is said to instantiate the Automobile class. Each object has a name. In Figure 1-1, the names are bobsCar, suesCar, and jakesTruck. In a Java program, bobsCar, suesCar, and jakesTruck would be variables of type Automobile. So among other things, a class is a data type. The definition of the Automobile class says that an Automobile object has data such as its model, its year, and how much fuel is in its tank. The class definition contains no actual data—no string and no numbers. The individual objects have the data, and the class simply specifies what kind of data they have. The Automobile class also defines methods such as goForward and goBackward. In a program that uses the class Automobile, the only actions an Automobile object can take are defined by those methods. All objects of a given class have exactly the same methods. The implementations of the methods indicate how the actions are performed and are included in the class definition. The objects themselves actually perform the method’s actions, however. The objects in a single class can have different characteristics. Even though these objects have the same types of data and the same methods, the individual objects can differ in the values of their data. Note: An object is a program construct that contains data and performs actions. The objects in a Java program interact, and this interaction forms the solution to a given problem. The actions performed by objects are called methods. Note: A class is a type or kind of object. All objects in the same class have the same kinds of data and the same methods. A class definition is a general description of what that object is and what it can do. Using the Methods in a Java Class Figure 1-1 7 An outline of a class and three of its instances The Class Automobile Class Name: Automobile Data: model_____________ year______________ fuelLevel_________ speed_____________ mileage___________ Methods (actions): goForward goBackward accelerate decelerate getFuelLevel getSpeed getMileage Objects (Instantiations) of the Class Automobile bobsCar suesCar jakesTruck Data: model: Sedan year: 2000 fuelLevel: 90% speed: 55 MPH mileage: 21,405 Data: model: SUV year: 2001 fuelLevel: 45% speed: 35 MPH mileage: 9,864 Data: model: Truck year: 1999 fuelLevel: 20% speed: 20 MPH mileage: 38,631 Methods: goForward goBackward accelerate decelerate getFuelLevel getSpeed getMileage Methods: goForward goBackward accelerate decelerate getFuelLevel getSpeed getMileage Methods: goForward goBackward accelerate decelerate getFuelLevel getSpeed getMileage Note: You can view a class in several different ways when programming. When you instanti- ate an object of a class, you view the class as a data type. When you implement a class, you can view it as a plan or a blueprint for constructing objects—that is, as a definition of the objects’ data and actions. At other times, you can think of a class as a collection of objects that have the same type. Using the Methods in a Java Class 1.2 Let’s assume that someone has written a Java class called Name to represent a person’s name. We will describe how to use this class and, in doing so, we will show you how to use a class’s methods. 8 CHAPTER 1 Java Classes The program component that uses a class is called the client of the class. We will reserve the term “user” to mean a person who uses a program. To declare a variable of data type Name, you would write, for example, Name joe; At this point, the variable joe contains nothing in particular; it is uninitialized. To create a specific object of data type Name—that is, to create an instance of Name— called joe, you write joe = new Name(); The new operator creates an instance of Name by invoking a special method within the class, known as a constructor. The memory address of the new object is assigned to joe, as Figure 1-2 illustrates. We will show you how to define constructors a bit later, in Segment 1.17. Note that you can combine the previous two Java statements into one: Name joe = new Name(); Figure 1-2 A variable that references an object joe 1.3 Object of type Name Suppose that a person’s name has only two parts: a first name and a last name. The data associated with the object joe then consists of two strings that represent the first and last names. Since you want to be able to set a person’s name, the Name class should have methods that give you this capability. To set joe’s first and last names, you use two methods from the class Name—setFirst and setLast—as follows: joe.setFirst("Joseph"); joe.setLast("Brown"); A method defined within a class is usually invoked by an object such as joe. You write the name of the calling object (joe) first, followed by a dot, the name of the method to be invoked, and finally a set of parentheses that contain arguments. In this example, the arguments are strings that represent inputs to the methods. The methods set the object’s data fields to the specific values given as arguments. The methods setFirst and setLast are examples of void methods, in that they do not return a value. A second kind of method—the valued method—returns a single value. For example, the method getFirst returns a string that is the invoking object’s first name. Similarly, the method getLast returns the last name. You can invoke a valued method anywhere that you can use a value of the type returned by the method. For example, getFirst returns a value of type String, and so you can use a method invocation such as joe.getFirst() anywhere that it is legal to use a value of type String. Such places could be in an assignment statement, like String hisName = joe.getFirst(); or within a println statement like System.out.println("Joe's first name is " + joe.getFirst()); Notice that the methods getFirst and getLast have no arguments in their parentheses. Any method—valued or void—can require zero or more arguments. Using the Methods in a Java Class 9 Note: Valued methods return a single value; void methods do not return a value. For example, the valued method getFirst returns the string that represents the first name. The void method setFirst sets the first name to a given string but does not return a value. Question 1 name. Write a Java statement that creates an object of type Name to represent your Question 2 Write a Java statement that uses the object you created in Question 1 to display your name in the form last name, comma, first name. Question 3 Which methods of the class Automobile, as given in Figure 1-1, are most likely valued methods, and which are most likely void methods? References and Aliases 1.4 Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean. A variable of a primitive type actually contains the primitive value. All other data types are reference, or class, types. The String variable greeting in String greeting = "Hello"; is a variable of a reference type or, more simply, a reference variable. A reference variable contains the address in memory of an actual object. This address is called a reference. It is not important here to know that greeting contains a reference to the string "Hello" instead of the actual string. In such cases, it is easier to talk about the string greeting, when in fact this is not an accurate description of that variable. The chapters in this book make the distinction between an object and a reference to an object when it is important to do so. Now suppose that you write Name jamie = new Name("Jamie", "Jones"); Name friend = jamie; The two variables jamie and friend reference the same instance of Name, as Figure 1-3 shows. We say that jamie and friend are aliases, because they are two different names for the same object. You can use jamie and friend interchangeably when referencing the object. Figure 1-3 Aliases of an object jamie "Jamie" "Jones" friend For example, if you use the variable jamie to change Jamie Jones’s last name, you can use the variable friend to access it. Thus, the statements jamie.setLast("Smith"); System.out.println(friend.getLast()); 10 CHAPTER 1 Java Classes display Smith. Also note that the boolean expression jamie == friend is true, since both variables contain the same address. Arguments and Parameters 1.5 Earlier you saw that an object of a class usually invokes the methods defined within the class. For example, you saw that the statements Name joe = new Name(); joe.setFirst("Joseph"); joe.setLast("Brown"); set the first and last names for the object joe. The strings "Joseph" and "Brown" are the arguments. These arguments must correspond to the formal parameters of the method definition. In the case of setFirst, for example, the formal parameter is the string firstName. The argument is the string "Joseph". The argument is plugged in for the corresponding formal parameter. Thus, in the body of the method, firstName represents the string "Joseph" and behaves like a local variable. A method invocation must provide exactly as many arguments as there are formal parameters in the corresponding method definition. In addition, the arguments in the invocation must correspond to the formal parameters in the method’s definition with respect to both the order in which they occur and their data types. In some cases, however, Java will perform an automatic type conversion when the data types do not match. Programming Tip: The arguments in the invocation of a method must correspond to the formal parameters in the method’s definition with respect to number, order, and data type. Defining a Java Class 1.6 We now show you how to write the Java class Name that represents a person’s name. You store a class definition in a file whose name is the name of the class followed by .java. Thus, the class Name should be in the file Name.java. (While not absolutely necessary, we will store only one class per file.) The data in a Name object consists of the person’s first and last names as strings. The methods in the class will enable you to set and look at these strings. The class has the following form: public class Name { private String first; private String last; // first name // last name < Definitions of methods are here > ... } // end Name The word public simply means that there are no restrictions on where the class is used. That is, the class Name is available for use in any other Java class. The two strings first and last are called the class’s data fields or instance variables or data members. Each object of this class will have these two data fields inside of it. The word private that precedes the declaration of each data field means that only the methods within the class can refer to the data fields by their names first and Defining a Java Class 11 last. No other class will be able to do this. The words public and private are examples of an access modifier or visibility modifier, which specifies where a class, data field, or method can be used. 1.7 Since the data fields are private, how will a class that uses the class Name be able to change or look at them? You can define methods in a class that look at or change its data fields. You declare such methods to be public, so that anyone can use them. A method that enables you to look at the value of a data field is called an accessor method or query method. A method that changes the value of a data field is called a mutator method. Java programmers typically begin the names of accessor methods with get and the names of mutator methods with set. Because of this convention, accessor methods are sometimes called get methods or getters, and mutator methods are called set methods or setters. For example, the class Name will have methods that include getFirst, getLast, setFirst, and setLast. You may think that accessor methods and mutator methods defeat the purpose of making data fields private. On the contrary, they give the class control over its data fields. For example, a mutator method can check that any change to a data field is appropriate and warn you if there is a problem. The class would be unable to make this check if its data fields were public, since anyone could alter the fields. Note: An accessor (query) method enables you to look at the value of a data field. A mutator method changes the value of a data field. Typically, you begin the names of accessor methods with get and the names of mutator methods with set. Programming Tip: You should make each data field in a class private by beginning its dec- laration with the access modifier private. You cannot make any direct reference to a private data field’s name outside of the class definition. The programmer who uses the class is forced to manipulate the data fields only via methods in the class. The class then can control how a programmer accesses or changes the data fields. Within any of the class’s method definitions, however, you can use the name of the data field in any way you wish. In particular, you can directly change the value of the data field. Question 1 Is the method setFirst an accessor method or a mutator method? Question 2 Should a typical accessor method be valued or void? Question 3 Should a typical mutator method be valued or void? Question 4 What is a disadvantage of making a data field in a class public? Method Definitions 1.8 The definition of a method has the following general form: access-modifier use-modifier return-type method-name(parameter-list) { } method-body Any class can use a public method, but a private method can be used only by the class that defines it. Chapter 2 discusses the access modifier protected, and the section “Packages” of this chapter shows when you can omit the access modifier. 12 CHAPTER 1 Java Classes Note: Access (visibility) modifiers The words public and private are examples of access modifiers that specify where a class, method, or data field can be used. The use modifier is optional and in most cases is omitted. Briefly, a final method cannot be overridden in a derived class. An abstract method has no definition and must be overridden in a derived class. A static method is shared by all instances of the class. You will encounter these use modifiers later in this or the next chapters. Next comes the return type, which for a valued method is the data type of the value that the method returns. For a void method, the return type is void. You then write the name of the method and a pair of parentheses that contain an optional list of formal parameters and their data types. The formal parameters, or simply parameters, specify values or objects that are inputs to the method. So far, we have described the first line of the method definition, which is called the method’s signature or heading or declaration. After the signature is the method’s body—which is simply a sequence of Java statements—enclosed in curly braces. 1.9 As an example of a valued method, here is the definition of the method getFirst: public String getFirst() { return first; Body } // end getFirst } Signature This method returns the string in the data field first. The return type of this method is, therefore, valued method must always execute a return statement as its last action. The data type of the value returned must match the data type declared as the return type in the method’s heading. Notice that this particular method does not have formal parameters. String. A 1.10 Now let’s look at an example of a void method. The void method setFirst sets the data field first to a string that represents a first name. The method definition is as follows: public void setFirst(String firstName) { first = firstName; } // end setFirst This method does not return a value, so its return type is void. The method has one formal parameter, firstName, that has the data type String. It represents the string that the method should assign to the data field first. The declaration of a formal parameter always consists of a data type and a parameter name. If you have more than one formal parameter, you separate their declarations with commas. 1.11 Notice that the bodies of the previous two method definitions refer to the data field first by name. This is perfectly legal. Exactly whose data field is involved here? Remember that each object of this class contains a data field first. The data field first that belongs to the object invoking the method is the one involved. Java has a name for this invoking object when you want to refer to it Defining a Java Class 13 within the body of a method definition. It is simply this. For example, in the method setFirst you could write the statement first = firstName; as this.first = firstName; People use this either for clarity or when they want to give the parameter the same name as the data field. For example, you could name setFirst’s parameter first instead of firstName. Clearly, the statement first = first; in the method’s body would not work correctly, so instead you would write this.first = first; We typically will not use this. Note: Members Both the data fields and the methods are sometimes called members of the object, because they belong to the object. Note: Naming classes and methods The normal convention when naming classes and methods is to start all method names with a lowercase letter and to start all class names with an uppercase letter. Use a noun or descriptive phrase to name a class. Use a verb or action phrase to name a method. Note: Local variables A variable declared within a method definition is called a local variable. The value of a local variable is not available outside of the method definition. If two methods each have a local variable of the same name, the variables are different, even though they have the same name. 1.12 Methods should be self-contained units. You should design methods separately from the incidental details of other methods of the class and separately from any program that uses the class. One incidental detail is the name of the formal parameters. Fortunately, formal parameters behave like local variables, and so their meanings are confined to their respective method definitions. Thus, you can choose the formal parameter names without any concern that they will be the same as some other identifier used in some other method. For team programming projects, one programmer can write a method definition while another programmer writes another part of the program that uses that method. The two programmers need not agree on the names they use for formal parameters or local variables. They can choose their identifier names completely independently without any concern that some, all, or none of their identifiers might be the same. 14 CHAPTER 1 Java Classes Note: Use of the terms “parameter” and “argument” The use of the terms “formal parameter” and “argument” in this book is consistent with common usage, but people also use the terms “parameter” and “argument” interchangeably. Some people use the term “parameter” for both what we call (formal) parameters and what we call arguments. Other people use the term “argument” for both what we call (formal) parameters and what we call arguments. Passing Arguments 1.13 When a formal parameter has a primitive type such as int, the parameter is initialized to the value of the corresponding argument in the method invocation. The argument in a method invocation can be a literal constant—like 2 or 'A'—or it can be a variable or any expression that yields a value of the appropriate type. Note that the method cannot change the value of an argument that has a primitive data type. Such an argument serves as an input value only. This mechanism is known as the call-by-value parameter mechanism. When a formal parameter has a class type, the corresponding argument in the method invocation must be an object of that class type. The formal parameter is initialized to the memory address of that object.1 Thus, the formal parameter will serve as an alternative name for the object. This implies that the method can change the data in the object, if the class has mutator methods. The method, however, cannot replace an object that is an argument with another object. 1.14 Example. For example, if you adopt a child, you might give that child your last name. Suppose that you add the following method giveLastNameTo to the class Name that makes this change of name: public void giveLastNameTo(Name child) { child.setLast(last); } // end giveLastNameTo Notice that the formal parameter of this method has the type Name. Now if Jamie Jones adopts Jane Doe, the following statements would change Jane’s last name to Jones: public static void main(String args)2 { Name jamie = new Name("Jamie", "Jones"); Name jane = new Name("Jane", "Doe"); jamie.giveLastNameTo(jane); . . . } // end main Figure 1-4 shows the argument executes. jane and the parameter child as the method giveLastNameTo 1. The parameter mechanism for parameters of a class type is similar to call-by-reference parameter passing. If you are familiar with this terminology, be aware that parameters of a class type in Java behave a bit differently from call-by-reference parameters in other languages. 2. If you are not familiar with main methods and application programs, consult the beginning of Appendix A. Defining a Java Class Figure 1-4 15 The method giveLastNameTo modifies the object passed to it as an argument "Jane" "Doe" (a) Before calling the method giveLastNameTo "Jane" "Doe" (b) After passing the object jane to the method jane ? child jane child "Jane" "Jones" (c) Just before the method ends. "Jane" "Jones" (d) After the method completes execution jane child jane ? child 1.15 What happens if you change the method definition to allocate a new name, as follows? public void giveLastNameTo2(Name child) { child = new Name(child.getFirst(), last); } // end giveLastNameTo2 With this change, the invoking statement jamie.giveLastNameTo2(jane); has no effect on jane, as Figure 1-5 illustrates. The parameter child behaves like a local variable, so its value is not available outside of the method definition. 16 CHAPTER 1 Figure 1-5 Java Classes A method cannot replace an object passed to it as an argument "Jane" "Doe" (a) Before calling the method "Jane" "Doe" (b) After passing the object jane to the method "Jane" "Doe" (c) Just before the method ends jane ? child jane child jane "Jane" "Jones" child "Jane" "Doe" (d) After the method completes execution jane ? child Question 8 Consider a method definition that begins with the statement public void process(int number, Name aName) If jamie is defined as in Segment 1.14 and you invoke this method with the statement someObject.process(5, jamie); what values are given to the parameters within the definition of the method? Question 9 In Question 8, can the method process change the data fields in jamie? Question 10 In Question 8, can the method process assign a new object to jamie? A Definition of the Class Name 1.16 A complete definition for the class Name follows: public class Name { Defining a Java Class private String first; private String last; // first name // last name public Name() { } // end default constructor public Name(String firstName, String lastName) { first = firstName; last = lastName; } // end constructor public void setName(String firstName, String lastName) { setFirst(firstName); setLast(lastName); } // end setName public String getName() { return toString(); } // end getName public void setFirst(String firstName) { first = firstName; } // end setFirst public String getFirst() { return first; } // end getFirst public void setLast(String lastName) { last = lastName; } // end setLast public String getLast() { return last; } // end getLast public void giveLastNameTo(Name aName) { aName.setLast(last); } // end giveLastNameTo public String toString() { return first + " " + last; } // end toString } // end Name 17 18 CHAPTER 1 Java Classes We typically place data field declarations at the beginning of the class, but some people place them last. Java also allows you to intermix method definitions and data field declarations. Let’s examine some other details of this class definition. Constructors 1.17 Segment 1.2 mentioned that you create an object by using the new operator to invoke a special method called a constructor. A constructor allocates memory for the object and initializes the data fields. The method definition of a constructor has certain special properties. A constructor G G G Has the same name as the class Has no return type, not even void Has any number of formal parameters, including no parameters A class can have several constructors that differ in the number or type of parameters. A constructor without parameters is called the default constructor. A class can have only one default constructor. The definition of the default constructor for Name is public Name() { } // end default constructor This particular default constructor has an empty body, but it need not be empty. It could explicitly initialize the data fields first and last to values other than the ones Java assigns by default. Programming Tip: In the absence of any explicit initialization within a constructor, data fields are set to default values: Object types are null, primitive numeric types are zero, and boolean types are false. If a class depends on a data field’s initial value, its constructor should set these values explicitly. Standard default values have been known to change. If you do not define any constructors for a class, Java will automatically provide a default constructor—that is, a constructor with no parameters. If you define a constructor that has parameters but you do not define a default constructor—one without parameters—Java will not provide a default constructor for you. Because classes are often reused again and again, and because eventually you might want to create a new object without specifying parameters, your classes typically should include a default constructor. Programming Tip: Once you start defining constructors, Java will not define any other constructors for you. Most of the classes you define should include a default constructor. 1.18 The class Name contains a second constructor, one that initializes the data fields to values given as arguments when the client invokes the constructor: public Name(String firstName, String lastName) { first = firstName; last = lastName; } // end constructor Defining a Java Class This constructor has two parameters, such as firstName and lastName. 19 You invoke it with a statement Name jill = new Name("Jill", "Jones"); that passes first and last names as arguments. 1.19 After creating the object jill, you can change the values of its data fields by using the class’s set (mutator) methods. You saw that this step was in fact necessary for the object joe in Segment 1.2 since joe was created by the default constructor and had default values—probably null—as its first and last names. In either case, you should not invoke a constructor again to alter the data fields of an object unless the class does not provide set methods. Let’s see what would happen in the case of jill if you did invoke the constructor a second time. After you created the object, the variable jill contained the memory address of that object, as Figure 1-6a illustrates. If you now write the statement jill = new Name("Jill", "Smith"); a new object is created, and jill contains its memory address. The original object is lost, because no program variable has its address, as shown in Figure 1-6b. What happens to a memory location when the variables in your program no longer reference it? Periodically, the Java run-time environment deallocates such memory locations by returning them to the operating system so that they can be used again. In effect, the memory is recycled. This process is called automatic garbage collection. Note: Memory leak If the Java runtime environment did not track and recycle memory that a program no longer references, a program could use all the memory available to it and subsequently fail. If you use another programming language—C++, for example—you would be responsible for returning unneeded memory to the operating system for reuse. A program that failed to return such memory would have what is known as a memory leak. Java programs do not have this problem. Figure 1-6 An object (a) after its initial creation; (b) after its reference is lost (a) (b) "Jones" jill 1.20 "Jill" "Jones" "Jill" "Jill" "Smith" jill Notice the method setName in the class definition. Although setName could use assignment statements to initialize first and last, it instead invokes the methods setFirst and setLast. Since these methods are members of the class, setName can invoke them without preceding the name with an object variable and a dot. If you prefer, you can use this, and write the invocation as this.setFirst(firstName); When the logic of a method’s definition is complex, you should divide the logic into smaller pieces and implement each piece as a separate method. Your method can then invoke these other 20 CHAPTER 1 Java Classes methods. Such helping methods, however, might be inappropriate for a client to use. If so, declare them as private instead of public so that only your class can invoke them. Although it generally is a good idea for methods to call other methods to avoid repeating code, you need to be careful if you call public methods from the body of a constructor. For example, it is tempting to have the constructor mentioned in Segment 1.18 call setName. But another class derived from your class could change the effect of setName and hence of your constructor. Segment 2.17 in the next chapter elaborates on this issue. Programming Tip: If a helping method is not appropriate for public use, declare it as private. Question 11 What is a default constructor? Question 12 How do you invoke a constructor? Question 13 What happens if you do not define constructors for a class? Question 14 What happens if you do not define a default constructor but you do define a constructor that has parameters? Question 15 What happens when an object no longer has a variable that references it? The Method toString 1.21 The last method in the class is toString. This method returns a string that is the person’s full name. You can use this method, for example, to display the name that the object jill represents by writing System.out.println(jill.toString()); What is remarkable about toString is that Java will invoke it automatically when you write System.out.println(jill); For this reason, providing a class with a method toString is a good idea in general. If you fail to do so, Java will provide its own toString method, which produces a string that will have little meaning to you. The next chapter provides more detail about the toString method. Static Fields and Methods 1.22 Static fields. Sometimes you need a data field that does not belong to any one object. For example, a class could track how many invocations of the class’s methods are made by all objects of the class. Such a data field is called a static field, static variable, or class variable. You declare a static field by adding the reserved word static. For example, the declaration private static int numberOfInvocations = 0; defines one copy of numberOfInvocations that every object of the class can access. Objects can use a static field to communicate or to perform some joint action. In this example, each method increments numberOfInvocations. Such static fields normally should be private to ensure that access occurs only through appropriate accessor and mutator methods. Defining a Java Class 21 The definition of a named constant provides another example of a static field. The statement public static final double PI = 3.14159; defines a static field PI. The class has one copy of PI, rather than each object of the class having its own copy, as Figure 1-7 illustrates. Since PI is also declared as final, its value cannot change. But static fields in general can change value if you omit the modifier final. Figure 1-7 A static field PI versus a nonstatic field radius Class definition public class Circle { public static final PI = 3.14159; private double radius; . . . } // end Circle 1.23 Instances (objects) of the class radius Objects of the class Circle all reference the one static field PI but have their own copy of radius radius Static methods. Sometimes you need a method that does not belong to an object of any kind. For example, you might need a method to compute the maximum of two integers or a method to compute the square root of a number. These methods have no obvious object to which they should belong. In these cases, you can define the method as static by adding the reserved word static to the signature of the method. A static method or class method is still a member of a class. However, you use the class name instead of an object name to invoke the method. For example, Java’s predefined class Math contains several standard mathematical methods, such as max and sqrt. All of these methods are static, so you do not need—and in fact have no real use for—an object of the class Math. You call these methods by using the class name in place of a calling object. Thus, you write statements such as int maximum = Math.max(2, 3); double root = Math.sqrt(4.2); The definition of a static method cannot reference any data field in its class that is not static. It can, however, reference its class’s static fields. Likewise, it cannot invoke a nonstatic method of the class, unless it creates a local object of the class and uses it to invoke the nonstatic method. However, a static method can call other static methods within its class. Since every application program’s main method is static, these restrictions apply to main methods. Programming Tip: Every class can have a main method You can include a test of a class as a main method in the class’s definition. Anytime you suspect something is wrong, you can easily test the class definition. Since you—and others—can see what tests you performed, flaws in your testing will become apparent. If you use the class as a program, the main method is invoked. When you use the class to create objects in another class or program, the main method is ignored. 22 CHAPTER 1 Java Classes Question 16 What happens if you do not declare a constant data field as static? Packages 1.24 Using several related classes is more convenient if you group them together within a Java package. To identify a class as part of a particular package, you begin the file that contains the class with a statement like package myStuff; You then place all of the files within one directory or folder and give it the same name as the package. To use a package in your program, you begin the program with a statement such as import myStuff.*; The asterisk makes all public classes within the package available to the program. You could, however, replace the asterisk with the name of a particular class in the package that you want to use. You probably have already used packages provided by Java, such as the package java.io. Why did we just say “public classes”? What other kind of class is there? You can use an access modifier to control access to a class just as you can control access to a data field or method. A public class—whether it is within a package or not—is available to any other class. If you omit the class’s access modifier entirely, the class is available only to other classes within the same package. This kind of class is said to have package access. Similarly, if you omit the access modifier on data fields or methods, they are available by name inside the definition of any class within the same package but not outside of the package. You use package access in situations where you have a package of cooperating classes that act as a single encapsulated unit. If you control the package directory, you control who is allowed package access. The Java Class Library 1.25 C HAPTER S UMMARY Java comes with a collection of many classes that you can use in your programs. For example, Segment 1.23 mentioned the class Math, which contains several standard mathematical methods such as sqrt. This collection is known as the Java Class Library, and sometimes as the Java Application Programming Interface, or API. The classes in this library are distributed among several standard packages. For example, the class Math is a part of the package java.lang. From time to time, we will mention classes within the Java Class Library that are like or relevant to the classes that we will define. G An object is a program construction that contains data and can perform certain actions. When the program is run, the objects interact with one another to accomplish a particular task. The actions performed by objects are called methods. A class is a type or kind of object. All objects in the same class have the same kinds of data and the same methods. G An access modifier, such as public or private, specifies where you can use a class, method, or data field. Packages 23 G G A public method that returns the data in a private data field is called an accessor method. A public method that changes the data in a private data field is called a mutator method. G Valued methods return a single value; void methods do not return any value. G A method invocation must provide exactly the same number of arguments as there are formal parameters in the corresponding method definition. In addition, the arguments in the invocation must correspond to the method’s formal parameters in its definition with respect to the order in which they occur and their data types. In some cases, however, Java will perform an automatic type conversion when the data types do not match. G When a formal parameter has a primitive type such as int, the parameter is initialized to the value of the corresponding argument in the method invocation. When a formal parameter has a class type, the corresponding argument in the method invocation must be an object of that class type. The formal parameter is initialized to the memory address of that object. G A valued method must always execute a return statement as its last action. The data type of the value returned must match the data type declared as the return type in the method’s signature. G A variable declared within a method definition is called a local variable. The value of a local variable is not available outside of the method definition. If two methods each have a local variable of the same name, the variables are different, even though they have the same name. Java does not give an initial value to a local variable, regardless of its data type. G A constructor allocates memory for the object and initializes the data fields. A constructor has the same name as the class, has no return type, not even void, and has any number of formal parameters, including zero parameters. G A constructor without parameters is called the default constructor. A class can have only one default constructor. If you do not define any constructors for a class, Java automatically provides a default constructor. G When the logic of a method’s definition is complex, you should divide the logic into smaller pieces and implement each piece as a separate method. Your method can then invoke these other methods. If such helping methods are inappropriate for a client to use, declare them as private instead of public so that only your class can invoke them. G Every class can have a main method. If you use the class as a program, the main method is invoked. When you use the class to create objects in another class or program, the main method is ignored. G A static field or static method is associated with the class and not the individual objects of the class. G P ROGRAMMING T IPS A private data field is not accessible by name outside of the class definition. Within any of the class’s method definitions, you can use the data field name in any way you wish. In particular, you can directly change the value of the data field. However, outside of the class definition, you cannot make any direct reference to the data field name. The programmer who uses the class is forced to manipulate the data fields only via methods in the class. The class then can control how a programmer accesses or changes the data fields. A package is a group of related classes that you place into a single directory or folder. Classes within a package can access by name any field or method within any other class in the package, if the field or method has no access modifier or is not private. G All data fields in a class should be private. G You cannot make any direct reference to a private data field’s name outside of the class definition. 24 CHAPTER 1 Java Classes G G When you invoke a method, the arguments must correspond to the method’s formal parameters in its definition with respect to number, order, and data type. G In the absence of any explicit initialization within a constructor, data fields are set to default values: Object types are null, primitive numeric types are zero, and boolean types are false. G Once you start defining constructors, Java will not define any other constructors for you. Most of the classes you define should include a default constructor. G If a helping method is not appropriate for public use, declare it as private. G E XERCISES Provide public methods to look at or change the data fields in an object. Include a test of a class as a main method in the class’s definition. Anytime you suspect something is wrong, you can easily test the class definition. (Several exercises involve the class Name, as given in Segment 1.16.) 1. What is the difference between how a method handles a parameter of a primitive type and a parameter of a reference (class) type? 2. If you remove the default constructor from the class Name, what happens if you write the statement Name me = new Name(); 3. If you remove all constructors from the class Name, what happens if you write the statement Name me = new Name(); 4. Implement another constructor for the class Name that has as its only parameter an instance of Name. The constructor should create a new name object whose data fields have the same values as its parameter’s data fields. 5. Suppose that jack and jill are two distinct objects of the class Name. a. Write Java statements that create a variable friend as an alias of jack. b. What is the value of the boolean expression friend == jack? Why? c. What happens to the last names of jack and jill after the following statements execute? Explain your answer. jill.giveLastNameTo(friend); jack.giveLastNameTo(jill); 6. Add the following methods to the class Name, as defined in this chapter: /** Task: Changes the last name to the last name of aName. */ public void changeLastNameTo(Name aName) /** Task: Changes the last name to the string newLastName. */ public void changeLastNameTo(String newLastName) Packages 25 7. Write a static method readName suitable for a client of the class Name that returns a Name object. This object should have a first and last name that readName reads as strings from the keyboard. P ROJECTS 1. Define a class called Counter. An object of this class is used to count things, so it records a count that is a nonnegative whole number. Include methods to set the counter to a given integer, to increase the count by 1, and to decrease the count by 1. Be sure that no method allows the value of the counter to become negative. Also include an accessor method that returns the current count value and a method that displays the count on the screen. Write a program to test your class definition. 2. Write a class called Person that has two data fields, one for the person’s name and one for the person’s age. Include set and get methods for each of these data fields. Also include methods to test whether G G Two Person objects are equal—that is, have the same name and age One person is older than another Finally, include a toString method that returns a string consisting of a person’s name and age. Write a test program that demonstrates each method. 3. Define a class GenericCoin that represents a coin with no value or name. The coin should have a heads side and a tails side and should be able to tell you which side is up. You should be able to “toss” the coin so that it lands randomly either heads up or tails up. a. Write a program that tosses two coins 50 times each. Record and report how many times each coin lands heads up. Also report which coin landed heads up most often. b. Write a program that plays a simple coin-toss game. You ask the user to guess whether the coin will be heads or tails. Then you toss the coin, tell the user the results, announce whether the user’s guess was correct, and tabulate the results. The user can continue playing the game for as long as desired. When the user quits, display a summary of the game, including the number of coin tosses, the number of heads, the number of tails, the number of correct guesses, and the percentage of guesses that were correct. If desired, use graphics to illustrate the result of each coin toss. 4. Many games depend on the roll of two dice. Define a class Die that represents one n-sided die. The default value for n is 6. You should be able to roll the die and determine the value of its upper face. Use random numbers to simulate the roll of the die. If desired, use graphics to display this face. 5. The largest positive integer of type int is 2,147,483,647. Another integer type, long, represents integers up to 9,223,372,036,854,775,807. Imagine that you want to represent even larger integers. Design and implement a class Huge of very large nonnegative integers. The largest integer should contain at least 30 digits. Provide operations for the class that G Set the value of a nonnegative integer (provide both set methods and constructors) 26 CHAPTER 1 Java Classes G G G G G Return the value of a nonnegative integer as a string Read a large nonnegative integer (skip leading zeros, but remember that zero is a valid number) Write a large nonnegative integer (do not write leading zeros, but if the integer is zero, write a single zero) Add two nonnegative integers to produce the sum as a third integer Multiply two nonnegative integers to produce the product as a third integer You should handle overflow when reading, adding, or multiplying integers. An integer is too large if it exceeds MAX_SIZE digits, where MAX_SIZE is a named constant that you define. Write a test program that demonstrates each method. 6. Write a Java class CalendarDate that represents a calendar date consisting of a month, day, and year. You can use three integers to represent a date. For example, July 4, 1776, is month 7, day 4, and year 1776. Include reasonable constructors, set and get methods, and a toString method. In addition, provide methods that G G G G Determine whether two dates are equal Get the day of the week for the current date Determine whether the current year is a leap year Advance the current date by one day A year is a leap year if it is divisible by 4 but not by 100. If the year is divisible by 100, it is a leap year only if it is also divisible by 400. To determine the day of the week, you can use the following algorithm. First, define the following integers: G G G G M represents the month. M is 1 for March, 2 for April, and so on. M is 11 for January and 12 for February, but for these two months, subtract 1 from the year before proceeding. D represents the day of the month (1 through 31). C is the first two digits of the year (after any adjustment for January and February). Y is the last two digits of the year (after any adjustment for January and February). Now compute F = (26 M - 2)/10 + D + Y + Y/4 + C/4 - 2 C All divisions are integer divisions in the sense that you discard any remainders. Now let W = F (modulo 7) That is, you divide F by 7 and retain only the remainder. (The modulo operator is % in Java.) W now represents the day of the week: 0 is Sunday, 1 is Monday, and so on. Write a test program that demonstrates each method in your class. 7. Write a Java class Time that represents the time of day in hours and minutes on a 24-hour clock. Include constructors, set and get methods, a method that advances the time by a given number of minutes, and a toString method. Provide another method, similar to toString, that returns the current time in 12-hour notation. For example, toString might return the string "13:05", while the other method returns the string "1:05pm". Optionally, you can write a method that displays the time on a digital or analog clock face. Packages 27 8. A magic square is a square two-dimensional array of positive integers such that the sum of each row, column, and diagonal is the same constant. For example, 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 is a magic square because the sum of the integers in each row is 34, the sum of the integers in each column is 34, and the sum of the integers in each of the two diagonals (16 + 10 + 7 + 1 and 4 + 6 + 11 + 13) is 34. The size of this magic square array is 4 because it has 4 rows and 4 columns. Write a Java class Square to represent an n-by-n square array of integers. Include methods that set or return the square’s size n, read integers into the square, display the square, and determine whether the square is a magic square. Write a test program that demonstrates each method. ...
View Full Document

Ask a homework question - tutors are online