Using Objects
On your AP exam, 5–7.5% of questions will cover the topic Using Objects.
As mentioned, all values in Java belong to either a primitive type or a reference type. The numeric
primitive types were covered in the previous section. In this section, we will discuss reference types.
An object is a compound value that has attributes, or data, and methods that can access or manipulate the
attributes. A class is a blueprint, or template, for the objects of a certain type. A class specifies what
attributes and methods an object will have.
Constructing and Storing Objects
An object is created from a class by calling the class constructor along with the new keyword. The name of
a constructor is the same as the name of the class it belongs to, and it is followed by a (possibly empty) list
of values. These values are parameters, and they represent initial values that will be used to create the
object.
The signature of a constructor consists of the name of the constructor along with the list of types of
parameters that it expects. When calling the constructor, the parameter list provided must match the
signature. A class may define multiple constructors as long as their signatures differ; in such a case, the
constructor is said to be overloaded.
For example, the Rectangle class from the Java standard library contains, among others, the following
two constructors:
Rectangle(int width, int height)
Rectangle(int x, int y, int width, int height)
The following would be valid constructor calls:
new Rectangle(5, 6) // calls the first constructor
new Rectangle(-1, 2, 3, 8) // calls the second constructor
However, the following would not be valid:
new Rectangle(3.2, 1) // invalid since the first parameter is double
new Rectangle(1, 2, 3) // invalid since it has three parameters
An object needs to be stored in a variable whose type is compatible with the class the object belongs to. In
most cases, the type of the variable will exactly match the type of the object. An exception is discussed in
the section on inheritance.
A complete statement to construct and store a rectangle object, then, looks like this:
Rectangle myRectangle = new Rectangle(5, 6);
A variable that refers to an object, as opposed to a primitive value, is called a reference variable. The
name comes from the fact that the memory associated with it does not store the object itself, but rather a