Writing Constructors

Objects are created in programs by declaring a variable of the class and using the keyword new followed by a call to a constructor. Constructors set the initial values for the object’s instance variables. For example, here is how we create a Person object.

// To create a new object, write:
// ClassName variableName = new ConstructorName(arguments);
Person p = new Person("Pat","pat@gmail.com","123-456-7890");

In a new class, constructors are usually written after the instance variables and before any methods. They typically start with public and then the name of the class: public ClassName(). Unlike other methods, they do not have a return type, not even void, after the access modifier public. They can take parameters (specified in parentheses) for the data which is used to initialize the instance variables.

public class ClassName {

   /* Instance Variable Declarations -- not shown */

   /* Constructor - same name as Class, no return type */
   public ClassName() {
     /* Implementation not shown */
   }
}

Note

Constructors must have the same name as the class! Constructors have no return type!

Classes usually have more than one constructor. There are usually at least 2 constructors:

The attributes of an object and their values at a given time define that object’s state. The constructors initialize the object’s state by assigning initial values to the instance variables that the object has as its attributes.

Here are two constructors that could be written for the Person class. Notice that the first one initializes name, email, and phoneNumber to empty string “” as the default values. Most programmers use “” as the default value for String variables and 0 as the default value for int and double variables.

// default constructor: initialize instance vars to default empty strings
public Person() {
   name = "";
   email = "";
   phoneNumber = "";
}

// constructor: initialize all 3 instance variables to parameters
public Person(String initName, String initEmail, String initPhone) {
   name = initName;
   email = initEmail;
   phoneNumber = initPhone;
}

If there are no constructors written for a class, Java provides a no-argument default constructor where the instance variables are set to their default values. For int and double variables, the default value used is 0, and for String and other object variables, the default is null. However, if you do write at least one constructor, Java will not generate the default constructor for you, so you should write at least a constructor with no parameters and one with many parameters.

exercise Check Your Understanding

Practice

coding exercise Coding Exercise

The given Car class is already defined with the instance variables model and year, for example a Honda 2010 car. However, some of the code is missing. Fill in the code for the 2 constructors that are numbered 1 and 2. And fill in the code to call the constructors in the main method numbered 3. The car1 object should test the first constructor with default values and the car2 object should test the second constructor to create a Honda 2010 car. Run your program and make sure it works and prints out the information for both cars.

Constructors are used to set the initial state of an object by initializing its instance variables. The examples above have instance variables that are primitive types, but you can have other objects, reference types, as instance variables. For example, a Person class could have an Address object as an instance variable, and the Address class could have String instance variables for the street, city, and state.

When you pass object references as parameters to constructors or methods, they become aliases for the original object and can change it. If a constructor has an object instance variable, it can copy the referenced object in the parameter using new and the constructor of the referenced object like below so that it does not change the state of the original object. You will see more examples like this in later lessons.

public class Person {
  private String name;
  private Address addr; //Assumes an Address class is already defined

  // constructor: initialize instance variable and call Address constructor to make a copy
  public Person(String initName, Address initAddr) {
     name = initName;
     addr = new Address(initAddr.getStreet(),
                initAddr.getCity(), initAddr.getState());
  }
 }

Practice

Summary

  • Constructors are used to set the initial state of an object, which includes initial values for all instance variables.

  • When no constructor is written, Java provides a no-argument default constructor, and the instance variables are set to their default values (0 for int and double, null for objects like String).

  • Constructor parameters are local variables to the constructor and provide data to initialize instance variables.

You have attempted of activities on this page