next up previous
Next: 1.3 Java Mechanics Up: 1. From Scheme to Previous: 1.1 Introduction


1.2 What is an Object?

Before discussing the specifics of Java's object system, let's define what an object is. Within a computer program, an object consists of

No code other than the designated operations can access or modify object fields. The fields and methods of an object are often called the members of the object. Each member of an object has a unique identifying name.

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, and phone number represented as character strings. We defer discussion about how to represent the directory itself until Section 1.6.

Each entry object must include operations to retrieve the name, address, and phone number fields, respectively.

Let's summarize the form of a directory entry as a table:

    Fields:
        String name;
        String address;
        String phone;
	
    Methods:
        String getName();
        String getAddress();
        String getPhone();
This tabular description is not legal Java syntax. We will introduce the actual syntactic details in the next section of this chapter.

The three methods getName, getAddress, and getPhone do not take any explicit arguments because they are invoked by sending a ``method call'' to an object, called the receiver, 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.

The syntax for invoking the method m (with no arguments) on the object o is

m.o()
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 1.2.1: In the DrJava programming environment, load the program Entry.java, compile it, and type the following statements in the Interactions pane:

Entry e = new Entry("Corky","DH 3104","x 6042");
e.getName()
The first line defines a variable e as an Entry object with name field "Corky", address field "DH 3104", and phone field "x 6042". The second line is an expression that computes the name field of e. What value does the Java evaluator return for the name field of e?

Before we explain the Java code in the program Entry.java defining the methods getName, getAddress, and getPhone, we must discuss the syntax and primitive operations of Java.


next up previous
Next: 1.3 Java Mechanics Up: 1. From Scheme to Previous: 1.1 Introduction
Corky Cartwright 2002-08-09