What is a Constructor?

The easiest way to think of a constructor in object-oriented programming (OOP) languages is:

A method that you invoke when you create an object of a class = A constructor

But that is not exactly true. Constructors are similar to methods, as above, but:

1.     They must have the same name as the class in which they are defined.

2.     They cannot return a value, so they cannot have a return type.

3.     They cannot be called in the same way you call a regular method.

So, we can define a constructor as follows:

A constructor is a special kind of method that has the same name as the class, and lets you create objects of a class and initialize variables of the class.

We will use Java as the (Object-Oriented Programming) OOP language for the examples in this article. The most basic constructor looks like the following:

class MyClass {

MyClass() { // This is where you place the body of the method and the member variables of the class

          }

}

The constructor here is “My Class.” Notice it has the same name as the class in which it is declared, and that it does not have a return type.

Note that in JavaScript, though, an “object constructor function” does something similar to defining a class in Java. You would use the “function” keyword for this, and then use “new” to call the JavaScript constructor function and instantiate an object of the type defined by the constructor function, as in the following example:

function Rectangle(long_side, short_side) {  // the constructor function
this.length = long_side;
this.breadth = short_side;
}

var MySmallRectangle = new Rectangle(5, 3); //  instantiate one object of the Rectangle type using “new”

var MyBiggerRectangle = new Rectangle(200, 108); //  instantiate another object of the Rectangle type

You Use Constructors Without Knowing It

Each time you create an instance of a class, a constructor is invoked. That’s why it’s called a “constructor,” by the way: it “constructs” the instance.

It is logical to imagine that if a class doesn’t have a constructor, there must be something automatic going on—something that “constructs” an object when you instantiate a class. This happens behind the scenes.

For classes that don’t have constructors, the compiler creates a default constructor—more precisely, a “default no-parameter” or “default no-argument” constructor—at the time of program execution. Think of the default no-arg constructor as a built-in, default mechanism for object creation.

Further, if there are uninitialized instance variables in the class, the default constructor method initializes them with default values—for example, the value 0 for an integer variable.

Here is an example of the Java Default Constructor at work:

public class Main {

             int Uninitialized Integer; // An uninitialized instance variable

public static void main(String[] args) {

Main Object Instance = new Main(); // We’re creating a new instance of Main here, and the class Main doesn’t have a constructor—so the Java default constructor is called

             System.out.print("The default constructor has assigned a value of ");

             System.out.print(ObjectInstance.UninitializedInteger);

             System.out.println(" to the variable UninitializedInteger.");

             }

}

Output: The default constructor has assigned a value of 0 to the variable Uninitialized Integer.

As you might expect, if you define a constructor in a class, the “default no-argument” constructor doesn’t work anymore for that class.

So why do you need constructors?

Now that you know what a constructor does, and that a default constructor is created by the compiler if you don’t write one for a class, it might seem unnecessary to use constructors.

Technically speaking, this is true. After all, you can instantiate objects of a class and initialize the variables of the class whenever you want.

However:

  • It is not good programming practice to initialize class variables outside the class.
  • Preventing errors—and error checking—are both easier if the data in a class is declared as private, and initialized within the class using the constructor of the class.

Types of Constructors

Constructors can be of three types:

  • The default constructor, which you’ve learned about
  • A no-argument constructor, which does not accept any arguments
  • A parameterized constructor, which does accept arguments

No-argument constructors

Here is an example of a no-argument (or no-arg) constructor in Java—a Java constructor that takes no arguments. As mentioned earlier, it is easier to prevent errors if the data in a class is declared as private—so let us declare it as private, and defining one integer variable, as in the following Java program:

public class Main {

             int IntegerVariable;

             private Main() { // This is a no-argument constructor

             IntegerVariable = 7;

             System.out.print("When we call the constructor, ");

             }

public static void main(String[] args) {

             Main NewInstance = new Main();

System.out.println("we see that the value of IntegerVariable is " + NewInstance.IntegerVariable + ".");

             }

}

Output: When we call the constructor, we see that the value of Integer Variable is 7.

Parameterized constructors

Here is an example of a parameterized constructor in Java—one that accepts an integer—as follows. We’ll use it to create, one after the other, two instances of Main:

 public class Main {

             int InitializedVariable;

Main(int ValuePassedToConstr) { //This accepts an integer as a parameter

             InitializedVariable = ValuePassedToConstr;

System.out.println("A new instance of this class has been created. The value passed to the constructor is " + InitializedVariable + ".");

}

public static void main(String[] args) {

             Main FirstInstance = new Main(11); // Create the first instance of Main

             Main SecondInstance = new Main(12); // Create the second instance of Main

             }

}

Java Compiler Output

A new instance of this class has been created. The value passed to the constructor is 11.

A new instance of this class has been created. The value passed to the constructor is 12.

In the program above:

  • We created an instance of the Main class two times.
  • The Main class has a constructor that takes an integer as a parameter.
  • Each of the two times, the constructor took the value passed to it and executed the statements within its body.

The Main class in the above example code has two constructors, one that accepts an integer as a parameter and another that accepts a string. The code creates two instances of the Main class. “First Instance” invokes the constructor that accepts an integer parameter, and “Second Instance” invokes the constructor that accepts a string parameter. Thus, the code invokes the appropriate constructor based on the parameter that is passed while creating an instance of Main. The constructor that is invoked accepts the value passed to it and executes the statements within its body.

Constructor Overloading

Constructor overloading is similar to method overloading in Java. It just means creating more than one constructor in the same class with different numbers or types of parameters as you’d expect, all the “overloaded” constructors need to have the same name as the class.

To illustrate the concept, let us use the same example as the one you just saw—creating two parameterized instances of the Main class. This time, one constructor in the Main class will accept an integer as a parameter—as in the previous example—and one will accept a string.

public class Main {

             int InitializedInteger;

             String InitializedString;

Main(int IntegerValuePassedToConstr) { //This accepts an integer as a parameter

             InitializedInteger = IntegerValuePassedToConstr;

System.out.println("A new instance of this class has been created. The constructor that accepts an integer was invoked. The value passed to the constructor is " + InitializedInteger + ".");

             }

Main(String StringValuePassedToConstr) { //This one accepts a string as a parameter

             InitializedString = StringValuePassedToConstr;

System.out.println("A new instance of this class has been created. The constructor that accepts a string was invoked. The value passed to the constructor is " + InitializedString + ".");

             }

             public static void main(String[] args) {

             Main FirstInstance = new Main(11); // Create the first instance of Main

             Main SecondInstance = new Main("STRING");

 // Create the second instance of Main

             }

}

Java Compiler Output

A new instance of this class has been created. The constructor that accepts an integer was invoked. The value passed to the constructor is 11.

A new instance of this class has been created. The constructor that accepts a string was invoked. The value passed to the constructor is STRING.

Here,

  • We created an instance of the Main class two times.
  • The Main class has two constructors, one that accepts an integer as a parameter and one that accepts a string.
  • Each of the two times, which constructor was called was based on the parameter that was passed while creating an instance of Main. The constructor that was called took the value passed to it and executed the statements within its body.

Common Mistakes

Here are a couple errors you’re likely to make when writing constructors in Java.

1. Accessing a constructor declared as private

You’ve learned that it is easier to prevent errors if the data in a class is declared as private. Remember that when you declare a constructor as private, it cannot be accessed from outside the Main class. The following code will give an error:

class ExampleClass { //We’re defining this class outside the Main class

            int IntegerVariable;

private ExampleClass() { // This is a no-argument constructor for ExampleClass, which we’ll try and call from outside the class

            IntegerVariable = 7;

            System.out.print("When we call the constructor, ");

            }

}

public class Main {
public static void main(String[] args) {

            ExampleClass NewInstance = new ExampleClass();

            System.out.println("we see that the value of IntegerVariable is " + NewInstance.IntegerVariable + ".");

            }
}

Java Compiler Error: Main.java:18: error: Example Class () has private access in Example Class

If you want to access Example Class constructor from outside the class, you cannot declare the constructor as private. You will need to declare it as public. So changing “private Example Class ()” to “public Example Class ()” gives the following output:

Output: When we call the constructor, we see that the value of Integer Variable is 7.

2. Imagining the default no-arg constructor when none exists

You’ve learned that once you’ve defined a constructor for a class, the default constructor is not called when you instantiate an object of the class. Say you define a parameterized constructor for a class “Big Rectangle,” which takes “width” and “height” as arguments. It is easy to imagine that the compiler “knows” what “Big Rectangle” means, and so try and create a new Big Rectangle using

myRectangle = new BigRectangle();

This will result in an error because the width and height have not been passed.

3. Assuming that a constructor will be inherited

After defining Big Rectangle as above, you might create a subclass called Square using “extends”—and then try to create a Square by passing a width and an (equal) height as arguments. This won’t work; you need to define a constructor within the Square subclass.

Context and Applications

You’ve seen that you can rely on the default constructor to instantiate an object. This, however, means that you can’t initialize the object attributes with their default, or desired, values at the same time as object creation—which is more efficient, and which is what a constructor achieves.

You’ve also seen that it is not good programming practice to initialize the variables of a class outside the class.

Want more help with your computer science homework?

We've got you covered with step-by-step solutions to millions of textbook problems, subject matter experts on standby 24/7 when you're stumped, and more.
Check out a sample computer science Q&A solution here!

*Response times may vary by subject and question complexity. Median response time is 34 minutes for paid subscribers and may be longer for promotional offers.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Introduction to Object Oriented Programming Concepts

Class

Constructor Homework Questions from Fellow Students

Browse our recently answered Constructor homework questions.

Search. Solve. Succeed!

Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.

Tagged in
EngineeringComputer Science

Programming

Introduction to Object Oriented Programming Concepts

Class