Before discussing the specifics of Java's object system, let's define what an object is. Within a computer program, an object consists of
To make the notion of object more concrete, let us consider a simple example. Assume that we want to maintain a directory containing the office address and phone number for each person in the Rice Computer Science Department. In Java, each entry in such a directory has a natural representation as an object with three fields containing the person's name, address (building and office number), and phone number (a Rice extension) represented as character strings. We defer discussion about how to represent the directory itself until Section 1.5.
Each entry object must support operations to retrieve the name, address, and phone number fields, respectively.
Let's summarize the form of a directory entry as a table:
This tabular description is not legal Java syntax. We will introduce the actual syntactic details later in the next section of the chapter.Fields: String name; String address; String phone; Methods: String getName(); String getAddress(); String getPhone();
The three methods getName, getAddress, and getPhone do not take any arguments because they are invoked by sending the ``method call'' to an object, called the receiver (or target in Java circles) which serves as an implicit argument for the method. In Java, the code defining the method can refer to this implicit argument using the keyword this, which is reserved for this purpose.
Consider the following example: assume that a Java program can access an Entry object e and needs to get the value of the name field of this object. The method invocation
e.getName()returns the desired result.
Finger Exercise: In the DrJava programming environment, load the library program DeptDir and type following statements in the Interactions window:
The first line defines a variable e as an Entry object with name field "Corky", address field "DH 3104", and phone field "x 6042". What value does the Java evaluator return for the name field of e?Entry e = new Entry("Corky","DH 3104","x 6042"); e.getName()
Before we explain the Java code in the library program DeptDir defining the methods getName, getAddress, and getPhone, we must discuss the syntax and primitive operations of Java.