5. Objects: Using, Creating, and Defining

5.5. Special Topic: Alan Kay and the Smalltalk Language

Although Simula was the first programming language to use the con- cept of an object, the first pure object-oriented language was Smalltalk. Smalltalk was first started by Alan Kay in the late 1960s. Kay is an innovative thinker who has had a hand in the development of several advances, including windowing interfaces, laser printing, and the clien- t/server model, all of which are now commonplace today.

One of the abiding themes throughout Kay’s career has been the idea that computers should be easy enough for kids to use. In the late 1960s, while still in graduate school, Kay designed a computer model that con- sisted of a notebook-sized portable computer with a keyboard, screen, mouse, and high-quality graphics interface. He had become convinced that graphics and icons were a far better way to communicate with a computer than the command-line interfaces that were prevalent at the time.

In the early 1970s Kay went to work at the Xerox Palo Alto Research Center (PARC), where he developed a prototype of his system known as the Dynabook. Smalltalk was the computer language Kay developed for this project. Smalltalk was designed along a biological model, in which individual entities or “objects” communicate with each other by passing messages back and forth. Another goal of Smalltalk was to enable children to invent their own concepts and build programs with them—hence, the name Smalltalk.

Xerox’s management was unable to see the potential in Kay’s innova- tions. However, during a visit to Xerox in 1979, Steve Jobs, the founder of Apple Computer, was so impressed by Kay’s work that he made it the inspiration of the Macintosh computer, which was first released in 1984.

Kay left Xerox in 1983 and became an Apple Fellow in 1984. In ad- dition to working for Apple, Kay spent considerable time teaching kids how to use computers at his Open School in West Hollywood. In 1996 Kay became a Fellow (an “Imagineer”) at the Walt Disney Imagineering’s Research and Development Organization, where he continues to explore innovative ways to enhance the educational and entertainment value of computers.

 

From the Java Library: java.util.Scanner.

 

If we wish to write useful interactive programs, we must be able to re- ceive information from the user as well as send information to him or her. We saw, in the previous chapter, that output from a program can be sent to the console window by simply using the System.out.print() and System.out.println() statements. In this section we describe two simple ways that Java can handle keyboard input. Receiving input from the keyboard, together with sending output to the console window, creates one of the standard user interfaces for programs.

Recall, that in Java, any source or destination for I/O is considered a stream of bytes or characters. To perform keyboard input, we will extract characters from System.in, the input stream connected to the keyboard. Getting keyboard input from System.in involves two complications that are not present in dealing with System.out.println(). First, normal keyboard input data requested of a user consists of a sequence of char- acters or digits which represent a word, phrase, integer, or real number. Normally, an entire sequence of characters typed by the user will repre- sent data to be stored in a single variable with the user hitting the return or enter key to signal the end of a piece of requested data. Java has a spe- cial class, BufferedReader, that uses an input stream and has a method that collects characters until it reads the character or characters that corre- spond to hitting the return or enter key. A second complication for reading input involves the problem of how to handle receiving data that is not in the same format as expected. The BufferedReader class handles this problem by using certain exceptions, a special kind of error message, that must be handled by the programmer. Chapter 11 is devoted to exceptions and we will avoid their use, as far as possible, until that time.

There is an alternate way to handle keyboard input in the Java 2 Plat- form Standard Edition 5.0 (Java SE 5.0). A Scanner class has been added to the java.util package which permits keyboard input without forc- ing the programmer to handle exceptions. We introduce the Scanner

class in the next subsection and then describe how a user defined class

introduced in Chapter 4 can function in an equivalent fashion to permit

 

Figure 2.25: The Scanner class, with a partial list of its public methods.


simple keyboard input.

 

Keyboard Input with the Scanner Class

 

A partial definition of Scanner is shown in Figure 2.25. Note that the Scanner methods listed are but a small subset of the public methods of this class. The Scanner class is in the java.util package so classes that use it should import it with the following statement:

,,

 

 

J

The Scanner class is designed to be a very flexible way to recognize chunks of data that fit specified patterns from any input stream. To use the Scanner class for keyboard input, we must create a Scanner in-

 

stance and associate it with System.in. The class has a constructor for this purpose, so the statement

,,

 

J

declares and instantiates an object that can be used for keyboard input. After we create a Scanner object, we can make a call to nextInt(), nextDouble(), or next() to read, respectively, an integer, real number, or string from the keyboard. The program in Figure 2.26 demonstrates how an integer would be read and used. When the nextInt() method

 

 

 

,,

 

 

 

 

 

 

 

 

\J

Figure 2.26: A very brief program with a Scanner object used for keyboard input

 

 

 

is executed, no further statements are executed until an int value is re- turned by the method. Normally this does not happen until the user has typed in the digits of an integer and hit the return or enter key. Thus ex- ecuting the main() method of the TestScanner class will result in the output

,,

 

J

to the console window and the program will wait for the user to type in an integer and hit the return or enter key. After this has been done the output will look something like:

,,

 

J

Keyboard input of real numbers and strings are handled in a similar manner.

 

Keyboard input will allow us to create examples of command line interfaces for interactive programs. For example, the code

,,

 

 

 

 

 

 

 

J

will display a riddle question and prompt the user to type a letter and to hit the enter key to see the answer. In the next chapter, we will develop new methods for the OneRowNim class that will be able to use int values input from the keyboard for the next move.

We must mention that, since the Scanner class is designed as a flexi- ble tool for recognizing chunks of data from any input stream, it has some properties that may be unexpected and not totally compatible with sim- ple keyboard input. A Scanner object has a set of character strings that separate or delimit the chunks of data that it is looking for. By default, this set of delimiters consists of any non-empty sequence of white space characters, that is, the space, tab, return, and newline characters. This will allow a user to input several integers separated by spaces before hitting the enter key. This might be handled by code like:

,,

 

 

J

White space as delimiters also means that the next() method cannot re- turn an empty string nor can it return a string that contains any spaces. For example, consider the code:

,,

 

J

If one types ”George Washington” and hits the enter key, the string str will store only ”George”. In order to get a Scanner object to read strings that contain spaces, we must use the useDelimiter() method to de- fine the set of delimiters as just that character string generated by hitting the enter key. For example, for some Windows operating systems, the statement

,,

 

J

 

will result in the next() method returning the entire string of charac- ters input from the keyboard up to but not including those generated by hitting the enter key.

You should also be aware that just because we can use a Scanner object to write Java code that ignores exceptions does not mean that exceptions will not be generated by keyboard input. If the user enters letters rather than digits for the nextInt() method to process, the program will be terminated with an error message.

It must be stressed that the strategy for handling keyboard input out- lined above is a temporary strategy until the topic of exceptions is cov- ered in Chapter 11. Real software applications that use keyboard input should carefully handle the possibility that a user will enter something unexpected. In Java, this can only be done by handling exceptions.

Keyboard Input with the KeyboardReader Class

If you are using an older version of Java that does not have the Scanner class, a user-defined class can be used instead. A KeyboardReader class that uses the BufferedReader class will be developed in Chap- ter 4. It has methods that read data from the keyboard in a manner very similar to those of the Scanner class. A partial list of its public meth- ods is given in the UML class diagram shown in Figure 2.27. To use the KeyboardReader class for keyboard input, copy the source code KeyboardReader.java from Chapter 4 into the same directory as the

source code of your current Java class (and add it to your current project

if you are using a integrated development environment).

 

To use a KeyboardReader object, we need to create an instance of the class with a constructor. Then calling one of the three methods will return an int, double, or String when data is input from the keyboard. Any of the three methods of a KeyboardReader object will attempt to process the entire string input from the keyboard up to the point that the enter key is hit. That is, the character or characters generated by hitting the return or enter key is the delimiter used by KeyboardReader. The TestKeyboardReader class definition in Figure 2.28 reads an integer


Figure 2.27: A UML class diagram of the KeyboardReader class.

 

,,

 

 

 

 

 

 

 

\J

Figure 2.28: A very brief program with a KeyboardReader object used for keyboard input.

 

from the keyboard and squares it just like the TestScanner class. In the remainder of the text, any time the Scanner class is used for keyboard

 

input, the same program can be run using the KeyboardReader class after making the obvious substitutions.

SELF-STUDY EXERCISES

EXERCISE 2.8Modify the main() method of the TestScanner class so that it reads a real number from the keyboard rather than an integer.

 

 

 

 

 

CHAPTER SUMMARYTechnical Terms

access modifier class-level variable default value delimiter

empty string flow of control interface


local variable method call and

return null pointer null pointer

exception pointer


reference reference variable static modifier user interface

 

Summary of Important Points

Dot notation is used to refer to an object’s public elements.

Designing a class is a matter of deciding what role it will play and what information and actions it will have.

Writing a Java program is a matter of defining one or more classes. A class definition serves as a template for creating instance of the class. Classes typically contain two kinds of elements, variables and meth- ods. An object’s state is defined by its instance variables.

Class elements that are declared public can be accessed by other objects. Elements that are declared private are hidden from other objects.

A class’s instance variables are usually declared private so they can- not be accessed directly by other objects.

An object’s public instance methods can be called by other objects. Thus, they make up the object’s interface with other objects.

Object instantiation is the process of creating an object, using the new

operator in conjunction with a constructor method.

A class definition consists of a header and a body. The header gives the class a name, specifies its accessibility (public), and its place in the Java class hierarchy (extends Object). The class body contains declarations of the class’s variables and definitions of its methods.

By default, a newly defined class is consider a subclass of Object. Class elements that are declared static, such as the main() method, are associated with the class (not with its instances).

A Java application program must contain a main() method, which is where it begins execution.

Methods that are used solely for the internal operations of the class should be declared private.

An instance variable declaration reserves memory for the instance

variable within the object, associates a name and a type with the lo- cation, and specifies its accessibility.

 

CHAPTER 2 Solutions to Self-Study Exercises95

A method definition consists of two parts: a header, which names the method and provides other general information about it, and a body, which contains its executable statements.

Declaring a variable creates a name for an object but does not create the object itself. An object is created by using the new operator and a constructor method.

 

 

 

 

SOLUTION 2.1 The Java code fragment prints out the following:

,,


 

SOLUTIONS TO

SELF-STUDY EXERCISES

 

 

J

 

SOLUTION 2.2 For the Riddle class (Fig. 2.12),

The name of the class: Riddle

The names of two instance variables: question, answer

The names of three methods: Riddle(), getQuestion(), getAnswer()

SOLUTION 2.3 For RiddleUser class (Fig. 2.15),

The names of two Riddle instances: riddle1, riddle2

All six method calls of the Riddle objects in the program:

,,

 

 

 

 

 

J

Qualified names: riddle1.getQuestion() and riddle1.getAnswer() SOLUTION 2.4 Definition of new instance variable in the Riddle class:

,,

 

J

 

SOLUTION 2.5 The header for a getHint() method of the Riddle class, which should be a public method, is:

,,

 

J

 

SOLUTION 2.6 The header for a setHint() method of the Riddle class is:

,,

 

J

The result type is void. Although the identifier used for the parameter is arbitrary, it is a good practice to make it descriptive, by referring in some way to the hint instance variable.

 

SOLUTION 2.7 The partial definition of the Student class is given below.

,,

 

 

 

 

 

 

 

J

 

SOLUTION 2.8 A main method that reads and squares a real number is given below.

,,

 

 

 

 

 

J

 

 

 

EXERCISES

Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.


EXERCISE 2.1 Consider the transaction of asking your professor for your grade in your computer science course. Identify the objects in this transaction and the types of messages that would be passed among them.

EXERCISE 2.2 Now suppose the professor in the previous exercise decides to automate the transaction of looking up a student’s grade and has asked you to design a program to perform this task. The program should let a student type in his or her name and ID number and the program then should display his or her grades for the semester, with a final average. Suppose there are five quiz grades, three exams, and two programming exercise grades. Identify the objects in this program and the type of messages that would be passed among them. (Hint: The grades themselves are just data values, not objects.)

EXERCISE 2.3 In the RiddleUser class (Fig. 2.15), give two examples of object instantiation and explain what is being done.

EXERCISE 2.4 Explain the difference between a method definition and a method call. Give an example of each from the Riddle and RiddleUser ex- amples discussed in this chapter.

EXERCISE 2.5 In the RiddleUser class (Fig. 2.15), identify three examples of method calls and explain what is being done.

EXERCISE 2.6 Describe how the slogan “define, create, manipulate” applies to the Riddle example.

EXERCISE 2.7 An identifier is the name for a,, or a.

 

EXERCISE 2.8 Which of the following would be valid identifiers?

,,

 

 

 

J

 

EXERCISE 2.9 Explain the difference between a class variable and an

instance variable.

 

EXERCISE 2.10 Identify the syntax error (if any) in each declaration. Remember that some parts of an instance variable declaration are optional.

public boolean isEven ;

Private boolean isEven ;

private boolean isOdd

public boolean is Odd ;

string S ;

public String boolean ;

private boolean even = 0;

private String s = helloWorld ;

 

EXERCISE 2.11 Write declarations for each of the following instance variables.

A private boolean variable named bool that has an initial value of true.

A public String variable named str that has an initial value of ”hello”.

A private int variable named nEmployees that is not assigned an initial value.

 

EXERCISE 2.12 Identify the syntax error (if any) in each method header:

public String boolean()

private void String ()

private void myMethod

private myMethod()

public static void Main (String argv[])

 

EXERCISE 2.13 Identify the syntax error (if any) in each assignment statement. Assume that the following variables have been declared:

 

,,

public

in t m;

 

 

 

 

 

public

boolean b ;

 

 

 

 

 

public

S t r i n g s ;

 

 

 

 

 

 

 

 

 

 

 

 

\J

a. m = "86" ;e. s = "1295" ;

b. m = 86 ;f. b = "true" ;

c. m = true ;g. b = false

d. s = 1295 ;

 

EXERCISE 2.14 Given the following definition of the NumberAdder class, add statements to its main() method to create two instances of this class, named adder1 and adder2. Then add statements to set adder1’s numbers to 10 and

 

15, and adder2’s numbers to 100 and 200. Then add statements to print their respective sums.

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

EXERCISE 2.15 For the NumberAdder class in the previous exercise, what are the names of its instance variables and instance methods? Identify three expres- sions that occur in the program and explain what they do. Identify two assignment statements and explain what they do.

EXERCISE 2.16 Explain the difference between each of the following pairs of concepts.

A method definition and a method call.

Declaring a variable of reference type and creating an instance.

A variable of reference type and a variable of primitive type.

EXERCISE 2.17 Define a Java class named NumberCruncher that has a single int variable as its only instance variable. Then define methods that perform the following operations on its number: get, double, triple, square, and cube. Set the initial value of the number with a constructor as was done with the instance variables in the Riddle class.

EXERCISE 2.18 Write a main() method and add it to the NumberCruncher class defined in the previous problem. Use it to create a NumberCruncher in- stance, with a certain initial value, and then get it to report its double, triple, square, and cube.

EXERCISE 2.19 Write a Java class definition for a Cube object, that has an inte- ger attribute for the length of its side. The object should be capable of reporting its surface area and volume. The surface area of a cube is six times the area of any side. The volume is calculated by cubing the side.

EXERCISE 2.20 Write a Java class definition for a CubeUser object that will use the Cube object defined in the previous exercise. This class should create three Cube instances, each with a different side, and then report their respective surface areas and volumes.

EXERCISE 2.21 Challenge: Modify your solution to the previous exercise so that it lets the user input the side of the cube. Follow the example shown in this chapter’s “From the Java Library” section.

 

EXERCISE 2.22 Challenge: Define a Java class that represents an address book entry, Entry, which consists of a name, address, and phone number, all repre- sented as Strings. For the class’s interface, define methods to set and get the values of each of its instance variables. Thus, for the name variable, it should have a setName() and a getName() method.

UML EXERCISES

EXERCISE 2.23 Draw a UML class diagram to represent the following class hi- erarchy: There are two types of languages, natural languages and programming languages. The natural languages include Chinese, English, French, and German. The programming languages include Java, Smalltalk and C++, which are object- oriented languages, FORTRAN, COBOL, Pascal, and C, which are imperative lan- guages, Lisp and ML, which are functional languages, and Prolog, which is a logic language.

EXERCISE 2.24 Draw a UML class diagram to represent different kinds of au- tomobiles, including trucks, sedans, wagons, SUVs, and the names and manufac- turers of some popular models in each category.

EXERCISE 2.25 Draw a UML object diagram of a triangle with attributes for three sides, containing the values 3, 4, and 5.

EXERCISE 2.26 Suppose you are writing a Java program to implement an elec- tronic address book. Your design is to have two classes, one to represent the user interface and one to represent the address book. Draw a UML diagram to depict this relationship. See Figure 2.14.

EXERCISE 2.27 Draw an UML object diagram to depict the relationship be- tween an applet, which serves as a user interface, and three Triangles, named t1, t2, and t3.

 

 

 

 

 

 

 

 

 

 

 

Chapter 3