Creating New Objects


The new keyword

One way to create a new object is to write new followed by the class of the object followed by arguments, in parentheses, that tell details about how to build the new object. For example,

  Integer two = new Integer(2);
creates a new object of class Integer that holds 2.

What you are allowed to write after new depends on the collection of constructors that have been provided for a given class. For example, new Integer(40) is allowed because the Integer class has a constructor that takes one argument of type int. As we explore classes we will see examples of constructors that are available.


Variables hold object references, not objects

Recall that a variable holds a reference to an object. So creating a new variable is not the same as creating a new object. It is important to keep that in mind. Imagine that there is a class Widget, and that class Widget supports a constructor that takes one integer argument. Then

  Widget x = new Widget(2);
  Widget y = x;
  Widget z;
creates three variables, but just one object. Variables x and y hold references to the same object. Variable z does not yet refer to any object.

Keep in mind that you use new to create a new object, not to create a new variable.