5.2. 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 World, Turtle, and Person objects.

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

Constructors don’t actually construct the objects. The class makes the object when you declare the object variable and then the constructor initializes the values of the instance variables.

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 ClassName()
{

}

Note

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

Classes usually have more than one constructor. There is usually at least a constructor that takes no parameters and a constructor that takes all the parameters necessary for initializing all the instance variables. 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

5-2-1: Click on all the parts of the constructorConstructors are public and have the same name as the class.
public class Name {

    private String first;
    private String last;

    public Name(String theFirst, String theLast) {
        first = theFirst;
        last = theLast;
     }

     public void setFirst(String theFirst) {
        first = theFirst;
     }

     public void setLast(String theLast) {
        last = theLast;
     }

}

    5-2-2: What best describes the purpose of a class’s constructor?

  • Determines the amount of space needed for an object and creates the object
  • The object is already created before the constructor is called but the constructor initializes the instance variables.
  • Names the new object
  • Constructors do not name the object.
  • Return to free storage all the memory used by this instance of the class.
  • Constructors do not free any memory. In Java the freeing of memory is done when the object is no longer referenced.
  • Initialize the instance variables in the object
  • A constructor initializes the instance variables to their default values or in the case of a parameterized constructor, to the values passed in to the constructor.

coding exercise Coding Exercise

The following class defines a Fraction with the instance variables numerator and denominator. It uses 2 constructors. Try to guess what it will print before you run it. You can also view it in the Java visualizer.

coding exercise Coding Exercise

The following class defines a Car 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.

5.2.1. groupwork Programming Challenge : Student Class

We encourage you to work in pairs for this challenge to create a Student class with constructors.

  1. First, brainstorm in pairs to do the Object-Oriented Design for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables?

  2. Write a Student class below that has your 4 instance variables and write at least 3 different constructors: one that has no parameters and initializes the instance variables to default values, one that has 4 parameters to set the instance variables, and one that has 1 parameter for the most important instance variable and uses defaults for the others.

  3. Add a print() method that uses System.out.println to print out all the instance variables.

  4. Add a main method that constructs at least 3 Student objects using the 3 different constructors and then calls their print() methods.

5.2.2. 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
Next Section - 5.3. Comments and Conditions