Basic Syntax

Constructors

🙋 Need help? Ask an expert now!

We mentioned constructors when we discussed declaring classes and we will visit this topic again later. For now, let's discuss what a constructor is and what it does. If a class is a description of a possible object, then the constructor is what functions to create the object of the class.

Constructors are often used with values called parameters that are stored in the data portion of the object that is created. Take a look at the program below. String parameterOne is the parameter of the constructor. The name of the constructor has to match the name of the class.

ConstructorsExample.java
package exlcode;

public class ConstructorsExample {
  private String exampleVariable;

  // this is the Default constructor of the class
  // that has no parameters
  public ConstructorsExample(){
  }

  // this is the constructor of the class
  // that takes in one parameter
  public ConstructorsExample(String parameterOne) {
    // this prints exampleVariable
    System.out.println(parameterOne);
  }

  public static void main(String[] args) {
    // this will be explained in Unit 8
    ConstructorsExample constructorsExample = new ConstructorsExample("Hello World!");
  }
}

Each class has at least one constructor. In the case that the programmer does not write a constructor definition, Java will produce a default constructor for that class. The default constructor will only perform the following basics: allocate memory and initialize instance variables. If we want more to happen when an object is created, we can include one or more constructors in the class definition. When declaring a constructor, remember that a constructor does not have any return type, not even void, so the header of the constructor should look something like this: public ClassName().

Edit Me on GitHub!

Application Question

What best describes the purpose of a constructor?