5. Objects: Using, Creating, and Defining

5.1. Introduction

This chapter introduces some more of the basic principles of object- oriented programming. We begin by looking at some examples of creat- ing and using objects of type String and Graphics. Then, we examine how user defined classes are used by doing a detailed walk-through of the Riddle class we saw in Chapter 1. We focus on the basic Java language elements involved. By the end of these sections, you should know how to identify the key elements that make up a Java program.

We then present a detailed example of the programming development process by designing a class that models a certain two person game and implements the class. The design is represented using UML notation.

 

Using String Objects

As we know, a Java program is a collection of interacting objects, where each object is a module that encapsulates a portion of the program’s at- tributes and actions. Objects belong to classes, which serve as templates or blueprints for creating objects. Think again of the cookie cutter analogy. A class is like a cookie cutter. Just as a cookie cutter is used to shape and create individual cookies, a class definition is used to shape and create individual objects.

Programming in Java is primarily a matter of designing and defining class definitions, which are then used to construct objects. The objects perform the program’s desired actions. To push the cookie cutter analogy a little further, designing and defining a class is like building the cookie cutter. Obviously, very few of us would bake cookies if we first had to design and build the cookie cutters. We’d be better off using a pre-built cookie cutter. By the same token, rather than designing our own classes, it will be easier to get into “baking” programs if we begin by using some predefined Java classes.

The Java library contains many pre-defined classes that we will use in our programs. So let’s begin our study of programming by using two of these classes, the String and Graphics classes.

Creating and Combining Strings

Strings are very useful objects in Java and in all computer programs. They

are used for inputting and outputting all types of data. Therefore, it

essential that we learn how to create and use String objects.

 

Figure 2.1: A partial representa- tion of the String class.


Figure 2.1 provides an overview of a very small part of Java’s String class. In addition to the two String() constructor methods, which are used to create strings, it lists several useful instance methods that can be used to manipulate strings. The String class also has two instance variables. One stores the String’s value, which is a string of characters such as “Hello98”, and the other stores the String’s count, which is the number of characters in its string value.

Recall from Chapter 0 that in order to get things done in a program we send messages to objects. The messages must correspond to the object’s instance methods. Sending a message to an object is a matter of calling one of its instance methods. In effect, we use an object’s methods to get the

 

object to perform certain actions for us. For example, if we have a String, named str and we want to find out how many characters it contains, we can call its length() method, using the expression str.length(). If we want to print str’s length, we can embed this expression in a print statement:

,,

 

J

In general, to use an object’s instance method, we refer to the method inDot notation

dot notation by first naming the object and then the method:

objectName.methodName() ;

The objectName refers to a particular object, and the methodName() refers to one of its instance methods.

As this example makes clear, instance methods belong to objects, and in order to use a method, you must first have an object that has that method. So, to use one of the String methods in a program, we must first create a String object.

To create a String object in a program, we first declare a String

variable.

,,

 

J

We then create a String object by using

the new keyword in conjunction with one of the String() construc-

tors. We assign the new object to the variable we declared:

,,Figure 2.2: A String object stores

a sequence of characters and a

Jcount giving the number of char-

 

This example will create a String that contains, as its value, the word ”Hello” that is passed in by the constructor. The String object that this creates is shown in Figure 2.2.

We can also use a constructor with an empty parameter list. Note that in this case we combine the variable declaration and the object creation into one statement:


acters.

 

,,

 

J

This example will create a String object that contains the empty string as its value. The empty string has the literal value ”” – that is, a pair of double quotes that contain no characters. Because the empty string has no characters, the count variable stores a zero (Fig. 2.3).

Note that we use a constructor to assign an initial value to a variable of

type String (or of a type equal to any other class). This differs from how

 

we assign an initial value to variables of primitive type, for which we use a simple assignment operator. This difference is related to an important difference in the way Java treats these two types of variables. Variables of primitive type are names for memory locations where values of prim- itive type are stored. As soon as they are declared they are assigned a default value of that primitive type. The default value for int is 0 and


Figure 2.3: The empty string has a value of ”” and a its length is 0.

 

the default value for boolean is false. On the other hand, variables that are declared to be of a type equal to a class name are designed to store a reference to an object of that type. (A reference is also called a pointer because it points to the memory address where the object itself is stored.) A constructor creates an object somewhere in memory and supplies a ref- erence to it that is stored in the variable. For that reason, variables that are declared as a type equal to a class name are said to be variables of reference type or reference variables. Reference variables have a special default value called null after they are declared and before they are as- signed a reference. It is possible to check whether or not a reference vari- able contains a reference to an actual object by checking whether or not it contains this null pointer.

Once you have constructed a String object, you can use any of the methods shown in Figure 2.1 on it. As we already saw, we use dot no- tation to call one of the methods. Thus, we first mention the name of the object followed by a period (dot), followed by the name of the method. For example, the following statements print the lengths of our two strings:

,,

 

J

Another useful String method is the concat(String) method, which can be used to concatenate two strings. This method takes a String argument. It returns a String that combines the String argument to the String that the method is called on. Consider this example:

,,

 

 

J

In this case, the concat() method adds the String s2 to the end of the String s1. The result, which gets printed, will be the String ”George Washington”.

Because strings are so important, Java allows a number of shortcuts to be used when creating and concatenating strings. For example, you don’t have to use new String() when creating a new string object. The following code will also work:

,,

 

J

Similarly, an easier way to concatenate two String objects is to use the plus sign (+), which serves as a concatenation operator in Java:

,,

 

J

Another useful String method is the equals() method. This is a boolean method, which is used to compare two Strings. If both Strings have the same characters, in the same order, it will return true.

 

Otherwise it will return false. For example, consider the following code segment:

,,

 

 

J

In this case, the expression s1.equals(s2) will be true, but s1.equals(s3) will be false.

It is important to note that the empty string is not the same as a String variable that contains null. Executing the statements:

,,

 

 

J

will not only not print out true; it will cause the the program to terminate abnormally. It is an error to use the method of a String variable, or any other variable whose type is a class, before it has been assigned an object. When the above code is executed, it will report a null pointer exception, one of the most common runtime errors. When you see that error mes- sage, it means that some method was executed on a variable that does not refer to an object. On the other hand, the empty string is a perfectly good String object which just happens to contain zero characters.

Figure 2.4 shows a program that uses string concatenation to create

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 2.4: A program that prints silly string puns.

 

some silly sentences. The programs declares a number of string variables, named s, s1, and so on, and it instantiates a String object for each vari- able to refer to. It then prints out a top-five list using the concatenation operator to combine strings. Can you figure out what it prints without running it?

 

SELF-STUDY EXERCISES

EXERCISE 2.1 What is the output to the console window when the following Java code fragment is executed:

,,

 

J